swift 3如何子类化NSDate或Date

时间:2016-12-16 07:18:04

标签: swift3

我正在尝试向JSONSerializable字段添加特殊dateTaken方法,因此我想扩展Date。但我发现Date是一个结构,不能扩展,所以NSDate。但我无法弄清楚如何从DateTaken

获得Date
class DateTaken : NSDate, JSONRepresentable {
    static var formatter = DateFormatter()

    var JSONRepresentation: AnyObject {
        DateTaken.formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"  // ISO8601
        DateTaken.formatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
        return DateTaken.formatter.string(from:self as Date) as AnyObject
    }
    var JSONLocalTimeRepresentation: AnyObject {
        DateTaken.formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
        return DateTaken.formatter.string(from:self as Date) as AnyObject
    }
}

let d = Date()
let dateTaken : DateTaken = DateTaken.init(timeInterval: 0, since: d)
// exception



(lldb) p NSDate.init(timeInterval: 0, since: dateTaken)
(NSDate) $R0 = 0x0000000156e6fdb0 2014-10-13 08:49:18 UTC
(lldb) p dateTaken.init(timeInterval: 0, since: dateTaken)
error: <EXPR>:3:1: error: 'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type
dateTaken.init(timeInterval: 0, since: dateTaken)
^
          type(of:  )

1 个答案:

答案 0 :(得分:0)

这不是Java。我们有扩展。

extension NSDate: JSONRepresentable {
    static var formatter = DateFormatter()

    var JSONRepresentation: AnyObject {
        DateTaken.formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"  // ISO8601
        DateTaken.formatter.timeZone = TimeZone(abbreviation: "UTC")
        return DateTaken.formatter.string(from: self as Date) as AnyObject
    }

    var JSONLocalTimeRepresentation: AnyObject {
        DateTaken.formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
        return DateTaken.formatter.string(from: self as Date) as AnyObject
    }
}

我还怀疑由于共享formatter而导致此错误。在timeZone中首次设置JSONRepresentation后,JSONLocalTimeRepresentation将像JSONRepresentation一样。我可能错了,但我现在无法测试。值得一试。