Skip to content

Instantly share code, notes, and snippets.

@gilesvangruisen
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save gilesvangruisen/30c95af0d3ad372ecdc0 to your computer and use it in GitHub Desktop.

Select an option

Save gilesvangruisen/30c95af0d3ad372ecdc0 to your computer and use it in GitHub Desktop.
StorableValue protocol for encoding/decoding a value type and StoredValue object for boxing up a StorableValue to be cached. (Value types can't conform to NSCoding because it's a class-protocol.)
protocol StorableValue {
typealias DecodedType = Self
public static func decode(json: NSData) -> DecodedType?
public func encode() -> NSData
}
final class StoredValue<T: StorableValue>: NSCoding {
private var data = NSData()
init(T: value) {
setValue(value)
}
// Set value
setValue(value: T) {
self.data = value.encode()
}
// Access value
value() -> T? {
return T.decode(data: self.data)
}
// MARK: NSCoding
required init(coder aDecoder: NSCoder) {
self.data = coder.decodeDataObject()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeDataObject(self.data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment