这是自助餐厅的营业时间
Monday - Thursday: 10:30 am - 12:00 am
Friday: 10:30 am - 9:00 pm
Saturday - Sunday: Closed
我正在实现一个函数,如果该地点根据当前时间打开或关闭,则返回一个状态.
在没有处理复杂的“if”语句的情况下,是否有更简单,更有效的方法来实现这样的事情?
func displayStatusForBrandywine () -> String
{
let currentDateTime = NSDate()
// get the user's calendar
let userCalendar = NSCalendar.currentCalendar()
// choose which date and time components are needed
let requestedComponents: NSCalendarUnit = [
NSCalendarUnit.Year,
NSCalendarUnit.Month,
NSCalendarUnit.Day,
NSCalendarUnit.Hour,
NSCalendarUnit.Minute,
NSCalendarUnit.Weekday
]
// get the components
let dateTimeComponents = userCalendar.components(requestedComponents, fromDate: currentDateTime)
var status: String = ""
if ((dateTimeComponents.weekday >= 2 && dateTimeComponents.weekday <= 5) && (dateTimeComponents.hour >= 10 && dateTimeComponents.hour <= 23) && (dateTimeComponents.minute <= 59 && dateTimeComponents.hour != 0) || ((dateTimeComponents.weekday == 6 && dateTimeComponents.hour >= 10 && dateTimeComponents.minute >= 30 && dateTimeComponents.hour <= 21) || (dateTimeComponents.weekday == 6 && dateTimeComponents.hour >= 11 && (dateTimeComponents.hour <= 21 && dateTimeComponents.minute < 0))))
{
status = "Open"
}
else
{
status = "Closed"
}
return status
}
最佳答案 这是一个有趣的方式来做到这一点……
struct OpenPeriod {
var day: Int
var openTime: Double
var closeTime: Double
func isOpen(dateTime: NSDate) -> Bool {
let userCalendar = NSCalendar.currentCalendar()
// choose which date and time components are needed
let requestedComponents: NSCalendarUnit = [
NSCalendarUnit.Hour,
NSCalendarUnit.Minute,
NSCalendarUnit.Weekday
]
// get the components
let dateTimeComponents = userCalendar.components(requestedComponents, fromDate: dateTime)
if dateTimeComponents.weekday != self.day { return false }
let timeOfDay = Double(dateTimeComponents.hour) + Double(dateTimeComponents.minute) / 60
return timeOfDay >= self.openTime && timeOfDay <= self.closeTime
}
}
var openingTimes = [OpenPeriod]()
openingTimes.append(OpenPeriod(day: 2, openTime: 10.5, closeTime: 12))
openingTimes.append(OpenPeriod(day: 3, openTime: 10.5, closeTime: 12))
openingTimes.append(OpenPeriod(day: 4, openTime: 10.5, closeTime: 12))
openingTimes.append(OpenPeriod(day: 5, openTime: 10.5, closeTime: 21))
func open(dateTime: NSDate) -> Bool {
return openingTimes.reduce(true, combine: { $0 && $1.isOpen(dateTime) })
}
open(NSDate()) ? "Open" : "Closed"