Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the current day of the week in Swift [duplicate]

Tags:

ios

swift

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
    }
}
like image 673
Yanir Avatar asked Feb 10 '23 18:02

Yanir


1 Answers

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
 }
like image 147
transistor Avatar answered Feb 13 '23 07:02

transistor