Skip to content

Instantly share code, notes, and snippets.

@smic
Created July 25, 2015 11:58
Show Gist options
  • Save smic/9ef1a01d6b53742dc858 to your computer and use it in GitHub Desktop.
Save smic/9ef1a01d6b53742dc858 to your computer and use it in GitHub Desktop.
First trial to implement lenses for any type
public struct Lense<T: AnyObject,V: Any> {
public let getter: () -> V
public let setter: (value: V) -> ()
init(getter: () -> V, setter: (value: V) -> ()) {
self.getter = getter;
self.setter = setter;
}
}
public class Line {
public var witdh: Int? = 2
public func lenseForProperty(name: String) -> Lense<Line, Any>? {
if (name == "witdh") {
// let lense = Lense<Line, Int?>(getter: { self.witdh }, setter: { self.witdh = $1 })
let lense = Lense<Line, Int?>(getter: { () -> Int? in
return self.witdh
}, setter: { (value) -> () in
self.witdh = value
})
return lense;
}
return nil
}
}
let line = Line()
if let lense = line.lenseForProperty("value") {
let witdh = lense.getter()
print("Width: \(witdh)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment