这是一个非常简单的问题,我正在使用代码段
获取一周的一天 if let weekday = getDayOfWeek("2017-05-01") {
print(weekday)
} else {
print("bad input")
}
func getDayOfWeek(_ today:String) -> Int? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
guard let todayDate = formatter.date(from: today) else { return nil }
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: todayDate)
return weekDay
}
我需要创建“工作日”,因为全局变量可以提供帮助。
我做的是:
class ViewController: UIViewController{
var weekday = NSInteger()
}
我在声明上面时收到了一些错误。
答案 0 :(得分:4)
将currentWeekDay
类型声明为Int
。
var weekday = Int()
现在使用if let
访问此实例属性。
if let weekday = getDayOfWeek("2017-05-01") {
//weekday has block scope and available only with in this if block
self.weekday = weekday
} else {
print("bad input")
}
修改:设置timezone
以获得正确的工作日
func getDayOfWeek(_ today:String) -> Int? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.timeZone = TimeZone(abbreviation: "UTC")!
guard let todayDate = formatter.date(from: today) else { return nil }
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: todayDate)
return weekDay
}