Skip to content

Instantly share code, notes, and snippets.

@Joony
Created November 4, 2022 09:44
Show Gist options
  • Save Joony/01d95b2b09d2434e7f97af14c3f877ae to your computer and use it in GitHub Desktop.
Save Joony/01d95b2b09d2434e7f97af14c3f877ae to your computer and use it in GitHub Desktop.
Convert a property into a function (a setter) so the value can be set as part of a function pipeline, or partially applied so the property can be set in response to specific events.
class Test {
var greeting = "Hello, playground"
}
let test = Test()
func setter<O: AnyObject, V>(_ obj: O, _ keyPath: ReferenceWritableKeyPath<O, V>) -> (V) -> () {
{ [weak obj] value in obj?[keyPath: keyPath] = value }
}
// Partial application
func papply<A, B>(_ a: A, _ f: @escaping (A) -> B) -> () -> (B) {
{ f(a) }
}
let f = papply("Wow", setter(test, \.greeting))
test.greeting // "Hello, playground"
f()
test.greeting // "Wow"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment