First you need to create an enumeration for the weekdays:
extension Date {
enum Weekday: Int {
case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
}
}
Second create an extension to return the next weekday desired:
extension Date {
var weekday: Int {
return Calendar.current.component(.weekday, from: self)
}
func following(_ weekday: Weekday) -> Date {
// **edit**
// Check if today weekday and the passed weekday parameter are the same
if self.weekday == weekday.rawValue {
// return the start of day for that date
return Calendar.current.startOfDay(for: self)
}
// **end of edit**
return Calendar.current.nextDate(after: self, matching: DateComponents(weekday: weekday.rawValue), matchingPolicy: .nextTime)!
}
}
Now you can use your method as follow:
let now = Date()
now.following(.sunday) // "Mar 10, 2019 at 12:00 AM"
now.following(.monday) // "Mar 11, 2019 at 12:00 AM"
now.following(.tuesday) // "Mar 12, 2019 at 12:00 AM"
now.following(.wednesday) // "Mar 6, 2019 at 12:00 AM"
now.following(.thursday) // "Mar 7, 2019 at 12:00 AM"
now.following(.friday) // "Mar 8, 2019 at 12:00 AM"
now.following(.saturday) // "Mar 9, 2019 at 12:00 AM"
5
solved Getting the first date from what a user has selected