4

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
    }
}
Yanir
  • 71
  • 1
  • 1
  • 2

1 Answers1

8

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
 }
Ulfalizer
  • 4,664
  • 1
  • 21
  • 30
transistor
  • 649
  • 6
  • 11