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.)
import Foundation
/**
The StorableValue protocol declares two functions for
encoding and decoding a Swift data structure to NSData
*/
protocol StorableValue {
typealias DecodedType = Self
class func decode(json: NSData) -> Self?
//func encode() -> NSData
}
/**
The StoredValue final class defines an NSCoding
conforming object used to encode/decode and box
a StorableValue so that it may be archived and
unarchived to/from any NSData cache.
*/
final class StoredValue<T: StorableValue>: NSObject, NSCoding {
private var data = NSData()
convenience init(value: T) {
self.init()
encode(value)
}
// MARK: NSCoding
convenience init(coder aDecoder: NSCoder) {
self.init()
self.data = aDecoder.decodeDataObject()!
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeDataObject(self.data)
}
// Set value
func encode(value: T) {
self.data = value.encode()
}
// Access value
func decode() -> T? {
return T.decode(self.data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment