Skip to content

Instantly share code, notes, and snippets.

@Pikaurd
Created November 8, 2018 02:54
Show Gist options
  • Save Pikaurd/c656a7b9a6968bdd461bd02a2fc8fb4a to your computer and use it in GitHub Desktop.
Save Pikaurd/c656a7b9a6968bdd461bd02a2fc8fb4a to your computer and use it in GitHub Desktop.
import UIKit
protocol StoredObject {
associatedtype Primitive
func toPrimitive() -> Primitive?
static func from(primitive: Primitive) -> Self?
}
protocol StoredAsSelf: StoredObject where Primitive == Self { }
extension StoredAsSelf {
func toPrimitive() -> Primitive? {
return self
}
static func from(primitive: Primitive) -> Primitive? {
return primitive
}
}
extension String: StoredAsSelf {
typealias Primitive = String
}
extension Int: StoredAsSelf {
typealias Primitive = Int
}
extension Float: StoredAsSelf {
typealias Primitive = Float
}
extension Date: StoredObject {
typealias Primitive = TimeInterval
func toPrimitive() -> Primitive? {
return timeIntervalSince1970
}
static func from(primitive: Primitive) -> Date? {
return Date(timeIntervalSince1970: primitive)
}
}
protocol StringLiteralBoilerplate {
init(stringLiteral value: String)
}
extension StringLiteralBoilerplate {
typealias StringLiteralType = String
init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
}
struct Storable<Object>: ExpressibleByStringLiteral, StringLiteralBoilerplate where Object: StoredObject {
private let key: String
private let store = UserDefaults.standard
init(stringLiteral value: String) {
self.key = value
}
var value: Object? {
set {
store.set(newValue?.toPrimitive(), forKey: key)
}
get {
guard let p = store.value(forKey: key) as? Object.Primitive else { return nil }
return Object.from(primitive: p)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment