Create a gist now

Instantly share code, notes, and snippets.

@owensd /kvc.swift Secret
Created Jul 3, 2015

What would you like to do?
KVC with Generics
protocol KeyValueCodable {
func value<T>(key: String) -> T?
func valueForKey(key: String) -> Any?
}
extension KeyValueCodable {
func value<T>(key: String) -> T? {
guard let value = valueForKey(key) else { return nil }
return value as? T
}
func valueForKey(key : String) -> Any? {
let mirror = reflect(self)
for index in 0 ..< mirror.count {
let (childKey, childMirror) = mirror[index]
if childKey == key {
return childMirror.value
}
}
return nil
}
}
struct Person {
var firstName: String
var lastName: String
}
extension Person : KeyValueCodable {}
var p = Person(firstName: "David", lastName: "Owens")
p.valueForKey("firstName")
p.valueForKey("middleName")
let s: String? = p.value("firstName")
let i: Int? = p.value("firstName")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment