我正在尝试获取当周的当前日期,以便根据日期更改图像。我的当前代码出错:"条件绑定中的绑定值必须是可选类型。"我对swift和ios很陌生,所以我不太确定要改变什么。
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
}
}
答案 0 :(得分:7)
您的错误消息是由于
行中的事实 if let todayDate = NSDate()
if let ...
在swift中有特殊含义。编译器尝试将可选变量绑定到常量。由于NSDate()
未返回可选值,因此这是一个错误。
取消if
,它应该有效:
func getDayOfWeek()->Int? {
let todayDate = NSDate()
let myCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let myComponents = myCalendar?.components(.WeekdayCalendarUnit, fromDate: todayDate)
let weekDay = myComponents?.weekday
return weekDay
}