Monday - Thursday: 10:30 am - 12:00 amFrIDay: 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,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,closeTime: 12))openingTimes.append(OpenPeriod(day: 4,closeTime: 12))openingTimes.append(OpenPeriod(day: 5,closeTime: 21))func open(dateTime: NSDate) -> Bool { return openingTimes.reduce(true,combine: { && .isOpen(dateTime) })}open(NSDate()) ? "Open" : "Closed"总结
以上是内存溢出为你收集整理的在Swift 2中实现时间帧的方法全部内容,希望文章能够帮你解决在Swift 2中实现时间帧的方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)