2016-12-16 15 views
1

を拡張したいので、私はメソッドをdateTakenフィールドに追加しようとしています。私はDateが構造体であり、拡張できないことを発見したので、NSDateです。しかし、私はDateswift 3 NSDateまたは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

「日付は構造体であり、拡張できません」とは何ですか? Extendはサブクラスと全く同じではありません。 – matt

+0

構造体( 'Date'など)は拡張できませんが、' NSDate'などのクラスは拡張できます。どちらの場合でも、あなたはしないでください。拡張子を使用してください。 – Alexander

+0

申し訳ありません。私はJSから来ています。私は、値が 'instanceof' DateTakenであるかどうかをテストしたいと思います。もしそうなら、私はそれを別々にシリアライズします。私はすべての日付を同じようにシリアル化したくありません。これを達成するために 'extensions 'をどうすれば使用できますか? – michael

答えて

0

からDateTakenを取得する方法を見つけ出すことはできませんこれは、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の共有によって引き起こされ、この中にバグがあります疑い。 timeZoneJSONRepresentationに初めて設定された後、JSONLocalTimeRepresentationJSONRepresentationのようになります。私は間違っているかもしれませんが、私は今それをテストすることはできません。それはチェックアウトの価値がある。

関連する問題