1
を拡張したいので、私はメソッドをdateTaken
フィールドに追加しようとしています。私はDate
が構造体であり、拡張できないことを発見したので、NSDate
です。しかし、私はDate
swift 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: )
「日付は構造体であり、拡張できません」とは何ですか? Extendはサブクラスと全く同じではありません。 – matt
構造体( 'Date'など)は拡張できませんが、' NSDate'などのクラスは拡張できます。どちらの場合でも、あなたはしないでください。拡張子を使用してください。 – Alexander
申し訳ありません。私はJSから来ています。私は、値が 'instanceof' DateTakenであるかどうかをテストしたいと思います。もしそうなら、私はそれを別々にシリアライズします。私はすべての日付を同じようにシリアル化したくありません。これを達成するために 'extensions 'をどうすれば使用できますか? – michael