我在编写将根据当前时间和当天名称执行功能的代码时遇到问题(例如,周日下午4点)。我已经在下面发布了我的代码,顺便说一句,我对此很新。我知道陈述是否是"懒惰"并且一旦满足一个条件,它就执行该语句并且不执行其余条件。
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day , .Month , .Year], fromDate: date)
let year = components.year
let month = components.month
let day = components.day
let componentFHM = calendar.components([ .Hour, .Minute, .Second], fromDate: date)
let hour = componentFHM.hour
let minute = componentFHM.minute
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE"
let dayOfWeekString = dateFormatter.stringFromDate(date)
print(dayOfWeekString)
if week[0] == dayOfWeekString {
if hour > 0 {
print("hello")
}
} else if week[6] == dayOfWeekString {
print("hello2")
}else{
print("Hello3")
}
if hour >= 9{
// if minute >= 0{
if minute >= 30{
if hour <= 18{
//if minute >= 0{
if minute <= 30{
print("Hello")
//I would put the function here.
}
}
}
}else if hour <= 0{
//if minute >= 0{
if minute <= 0{
if hour <= 0{
// if minute >= 0{
if minute >= 0{
print("HelloWorld")
}
}
}
}else{print("Hello Mac")}
答案 0 :(得分:1)
您可以使用switch语句:
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([ .Weekday, .Hour, .Minute], fromDate: NSDate())
switch ( components.weekday, components.hour, components.minute )
{
case ( 1, 7, 30 ) : print("Sunday 7H30, take a coffee and do you weekly run")
case ( 2...6, 6, _ ) : print("Weekdays, between 6 and 7 AM, get ready to work")
case ( 6, 17...23, _ ) : print("TGIF Party !!!")
default : break
}