Created
November 4, 2022 09:44
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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