我在编写基于当前时间和一天的名称(例如,星期日下午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")}
最佳答案
您可以使用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
}
关于swift - 如何执行相对于时间的功能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34736919/