Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Last active January 23, 2016 00:48
Show Gist options
  • Save chriseidhof/7cf7171388161e2d46e1 to your computer and use it in GitHub Desktop.
Save chriseidhof/7cf7171388161e2d46e1 to your computer and use it in GitHub Desktop.
Encoding
struct User {
let firstName: String
let lastName: String
let year: Int
}
enum JSONValue {
case JSONString(String)
case JSONInt(Int)
}
struct Key<In> {
let field: String
let get: In -> JSONValue
init(_ field: String, _ get: In -> String) {
self.field = field
self.get = { .JSONString(get($0)) }
}
init(_ field: String, _ get: In -> Int) {
self.field = field
self.get = { .JSONInt(get($0)) }
}
}
extension User {
static var firstNameKey: Key<User> { return Key("first_name", { $0.firstName }) }
static var lastNameKey: Key<User> { return Key("last_name", { $0.firstName }) }
static var yearKey: Key<User> { return Key("last_name", { $0.year} ) }
static var allKeys: [Key<User>] {
return [firstNameKey, lastNameKey, yearKey]
}
}
protocol Encodable {
static var allKeys: [Key<Self>] { get }
func encode() -> [String:JSONValue]
}
extension Encodable {
func encode() -> [String:JSONValue] {
return encodeKeys(Self.allKeys)
}
func encodeKeys(keys: [Key<Self>]) -> [String:JSONValue] {
var result: [String:JSONValue] = [:]
for key in keys {
result[key.field] = key.get(self)
}
return result
}
}
extension User: Encodable { }
let instance = User(firstName: "Bryan", lastName: "Irace", year: 2015)
print(instance.encode())
print(instance.encodeKeys([User.firstNameKey]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment