Skip to content

Instantly share code, notes, and snippets.

@waltflanagan
Last active August 29, 2015 14:26
Show Gist options
  • Save waltflanagan/0af371edbf68e938903a to your computer and use it in GitHub Desktop.
Save waltflanagan/0af371edbf68e938903a to your computer and use it in GitHub Desktop.
Strongly Typed NSCoding
public protocol NSCodingKey: RawRepresentable { }
extension NSCoder{
func encodeObject<T where T:NSCodingKey, T.RawValue == String>(objv: AnyObject?, forKey key: T) {
self.encodeObject(objv, forKey: key.rawValue)
}
func decodeObjectForKey<T where T:NSCodingKey, T.RawValue == String>(key: T) -> AnyObject?{
return decodeObjectForKey(key.rawValue)
}
}
class Book : NSObject, NSCoding {
let title:String
let author:String
private enum BookKey: String, NSCodingKey {
case Title
case Author
}
required init(coder aDecoder: NSCoder) {
self.title = aDecoder.decodeObjectForKey(BookKey.Title) as! String
self.author = aDecoder.decodeObjectForKey(BookKey.Author) as! String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.title, forKey: BookKey.Title)
aCoder.encodeObject(self.author, forKey: BookKey.Author)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment