Skip to content

Instantly share code, notes, and snippets.

@cwagdev
Last active August 29, 2015 14:24
Show Gist options
  • Save cwagdev/a7b1d38f80612f21dcd4 to your computer and use it in GitHub Desktop.
Save cwagdev/a7b1d38f80612f21dcd4 to your computer and use it in GitHub Desktop.

Revisions

  1. cwagdev renamed this gist Jul 14, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. cwagdev created this gist Jul 14, 2015.
    26 changes: 26 additions & 0 deletions Swift valueForKey
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    protocol ValueForKeyLookupable {
    func valueForKey(key: String) -> Any?
    }

    extension ValueForKeyLookupable {
    func valueForKey(key: String) -> Any? {
    let mirror = reflect(self)
    for index in 0..<mirror.count {
    let child = mirror[index]
    if key == child.0 {return child.1.value}
    }
    return nil
    }
    }

    struct Pt: ValueForKeyLookupable {
    let x: Int
    let y: Int
    init(_ x: Int, _ y: Int) {self.x = x; self.y = y}
    init(){self.init(0, 0)}
    }

    let p = Pt(2, 3)

    p.valueForKey("x")
    p.valueForKey("y")