在Swift中获取当周的当前日期 [英] Getting the current day of the week in Swift

查看:572
本文介绍了在Swift中获取当周的当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取当周的当前日期,以便根据日期改变图像。我的当前代码出错:条件绑定中的绑定值必须是可选类型。我对swift和ios很新,所以我不太清楚要改变什么。

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

如果让nowDate = NSDate()

如果让... 在swift中有特殊含义。编译器尝试将可选变量绑定到常量。由于 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.

不要 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
 }

这篇关于在Swift中获取当周的当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆