Is there some way to automatically generate a getter/setter function pair for a property in a class in Swift? Something along the lines of a lens in Haskell.
I've been able to do the following manually:
class PropertyLens<U, T> {
let getter: U -> T
let setter: (U, T) -> ()
init(getter: (U -> T), setter: ((U, T) -> ())) {
self.getter = getter
self.setter = setter
}
func get(u: U) -> T {
return getter(u)
}
func set(u: U, t: T) {
setter(u, t)
}
}
// ...
let myPropertyLens = PropertyLens<MyClass, Int>(getter: { $0.myProperty }, setter: { $0.myProperty = $1 })
However, that becomes verbose, tedious, and more error-prone than I'd like. Is there a built-in feature I'm missing?
willSet
anddidSet
handlers and computed properties, there's a lot of flexibility. – OverslaughU
&T
stand for? Side-note: You'll find that single-letter variable or type names are rare and discouraged in Swift; it make code much more readable to any Swift programmer if the each identifier is at least one word concisely describing its purpose. – Isodynamic