【问题标题】:How can I use NSCalendar range function within Calendar?如何在日历中使用 NSCalendar 范围功能?
【发布时间】:2018-10-20 05:23:29
【问题描述】:

我有以下代码在 Swift 2 中使用编译,但在 Swift 4.2 中不会。返回布尔值的范围函数不再是 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)
    }
}

【问题讨论】:

    标签: swift nscalendar


    【解决方案1】:

    Calendar 中的range(of:start:interval:for:) 等价于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)
        }
    }
    

    【讨论】:

    • 表示 dateInterval 函数未使用。您是说通过将结果转换为 DateInterval 数据类型基本上可以解决问题而不需要 dateInterval 函数?
    • 两个版本都应该以相同的方式工作。是说dateInterval 函数未使用 还是dateInterval 函数的结果 未使用。该函数本身显然没有被使用。
    • 如果您收到关于结果未使用的警告,请写_ = dateInterval(...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多