我有以下代码在Swift 2中使用了编译,但是在Swift 4.2中却没有。返回布尔值的range函数不再是Calendar数据类型的一部分,但是它是NSCalendar数据类型的一部分。有什么方法可以使用或格式化此函数以使其在Swift 4.2中编译?
extension Calendar {
/**
Returns a tuple containing the start and end dates for the week that the
specified date falls in.
*/
func weekDatesForDate(date: NSDate) -> (start: NSDate, end: NSDate) {
var interval: TimeInterval = 0
var start: NSDate?
range(of: .weekOfYear, start: &start, interval: &interval, for: date as Date)
let end = start!.addingTimeInterval(interval)
return (start!, end)
}
}
我尝试了以下操作,但是范围函数不相同并且无法编译:
extension NSCalendar {
/**
Returns a tuple containing the start and end dates for the week that the
specified date falls in.
*/
func weekDatesForDate(date: NSDate) -> (start: NSDate, end: NSDate) {
var interval: TimeInterval = 0
var start: NSDate?
range(of: .weekOfYear, start: &start, interval: &interval, for: date as Date)
let end = start!.addingTimeInterval(interval)
return (start!, end)
}
}
答案 0 :(得分:2)
range(of:start:interval:for:)
中Calendar
的等效项是dateInterval(of:start:interval:for:)
在Swift中不要使用NSDate
extension Calendar {
/**
Returns a tuple containing the start and end dates for the week that the
specified date falls in.
*/
func weekDatesForDate(date: Date) -> (start: Date, end: Date) {
var interval: TimeInterval = 0
var start = Date()
dateInterval(of: .weekOfYear, start: &start, interval: &interval, for: date)
let end = start.addingTimeInterval(interval)
return (start, end)
}
}
我建议使用专用的DateInterval
作为返回值而不是元组:
extension Calendar {
/**
Returns a tuple containing the start and end dates for the week that the
specified date falls in.
*/
func weekDatesForDate(date: Date) -> DateInterval {
var interval: TimeInterval = 0
var start = Date()
dateInterval(of: .weekOfYear, start: &start, interval: &interval, for: date)
let end = start.addingTimeInterval(interval)
return DateInterval(start: start, end: end)
}
}