Created
September 3, 2018 21:16
-
-
Save d-date/5475d1bdec354de5d8786a78c75290c2 to your computer and use it in GitHub Desktop.
When define prop as this, we can mutate property with function composition #CodePiece #tryswiftnyc
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
func prop<Root, Value>( | |
_ kp: WritableKeyPath<Root, Value> | |
) | |
-> (@escaping (Value) -> Value) | |
-> (Root) -> Root { | |
return { transformPart in | |
return { root in | |
var root = root | |
root[keyPath: kp] = transformPart(root[keyPath: kp]) | |
return root | |
} | |
} | |
} | |
user.age | |
let newUser = user | |
|> prop(\.age)(incr) | |
>>> (prop(\.name)) { $0.uppercased() } | |
newUser.age | |
newUser.name | |
[user, user, user] | |
|> map(prop(\.age)(incr) | |
>>> (prop(\.name)) { $0.uppercased() }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment