I am trying to get the current day of the week in order to change an image based on what day it is. I am getting an error with my current code: "Bound value in a conditional binding must be of Optional type." I'm pretty new to swift and ios, so I'm not quite sure what to change.
func getDayOfWeek()->Int? {
if let todayDate = NSDate() {
let myCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let myComponents = myCalendar?.components(.WeekdayCalendarUnit, fromDate: todayDate)
let weekDay = myComponents?.weekday
return weekDay
} else {
return nil
}
}
Your error message is due to the fact that in the line
if let todayDate = NSDate()
the if let ...
has a special meaning in swift. The compiler tries to bind a optional variable to a constant. As NSDate()
doesn't return an optional value, this is an error.
Leave off the if
and it should work:
func getDayOfWeek()->Int? {
let todayDate = NSDate()
let myCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let myComponents = myCalendar?.components(.WeekdayCalendarUnit, fromDate: todayDate)
let weekDay = myComponents?.weekday
return weekDay
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With