Getting the current day of the week in Swift

I am trying to get the current day of the week to change the image depending on the day. I get an error with my current code: "The bound value in the conditional binding must be an optional type." I am fairly new to fast 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
    }
}
+4
source share
1 answer

Your error message is due to the fact that in the line

if let todayDate = NSDate()

if let ...is of particular importance in fast. The compiler is trying to bind an optional variable to a constant. Since it NSDate()does not return an optional value, this is an error.

Leave the value ifand 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
 }
+7
source

All Articles