Swift, using NSCoding

I’ve uploaded a small playground available here to illustrate the use of NSCoding with custom Swift objects.

Every class that will be encoded and decoded need to implement the NSCoding protocol and be an Objective-C object.

class CustomPoint: NSObject, NSCoding {
}

You can extend the NSObject class as in the example above. You can also use the @objc annotation.

Object will be created using a specialized initialize:

required init?(coder aDecoder: NSCoder) {
    x = aDecoder.decodeDoubleForKey("x")
    y = aDecoder.decodeDoubleForKey("y")
}

And you will encode objects using a encodeWithCoder() method:

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeDouble(x, forKey: "x")
    aCoder.encodeDouble(y, forKey: "y")
}