Skip to content

Instantly share code, notes, and snippets.

@owensd

owensd/kvc.swift Secret

Created July 3, 2015 05:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owensd/22b6c24a614b091b7006 to your computer and use it in GitHub Desktop.
Save owensd/22b6c24a614b091b7006 to your computer and use it in GitHub Desktop.
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