Last active
August 29, 2015 14:23
-
-
Save RobJDavey/f17f53b1971366818c21 to your computer and use it in GitHub Desktop.
Using Swift Protocol Extensions for strongly typed coding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol CodingKeyType { | |
typealias CodingKey: RawRepresentable | |
} | |
extension CodingKeyType where Self: NSCoding, CodingKey.RawValue == String { | |
static func decodeObject<T: AnyObject>(inout objv: T?, fromCoder aDecoder: NSCoder, forKey key: CodingKey) { | |
guard let object = aDecoder.decodeObjectOfClass(T.self, forKey: key.rawValue) as? T? else { | |
fatalError("Failed to decode a value of type \(T.self)") | |
} | |
objv = object | |
} | |
static func encodeObject<T: AnyObject>(objv: T?, toCoder aCoder: NSCoder, forKey key: CodingKey) { | |
aCoder.encodeObject(objv, forKey: key.rawValue) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person: NSObject, NSCoding, CodingKeyType { | |
enum CodingKey: String { | |
case Name = "name" | |
} | |
let name: String | |
required init?(coder aDecoder: NSCoder) { | |
var name: NSString? | |
Person.decodeObject(&name, fromCoder: aDecoder, forKey: CodingKey.Name) | |
self.name = name as! String | |
} | |
func encodeWithCoder(aCoder: NSCoder) { | |
Person.encodeObject(name as NSString, toCoder: aCoder, forKey: CodingKey.Name) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment