Created
August 23, 2021 18:21
-
-
Save glukianets/e3ee27395af05e4edf86aaed0926c71c to your computer and use it in GitHub Desktop.
Poor man's lenses in swift
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
infix operator .=: AssignmentPrecedence | |
func .=<T, U>(_ kp: WritableKeyPath<T, U>, _ value: U) -> (inout T) -> () { | |
{ $0[keyPath: kp] = value } | |
} | |
protocol Cloneable { } | |
extension Cloneable { | |
func clone(with modifiers: (inout Self) -> ()...) -> Self { | |
return modifiers.reduce(into: self) { $1(&$0) } | |
} | |
} | |
struct Foo: Cloneable { | |
var bar: Bar | |
var baz: Baz | |
} | |
struct Bar { | |
var baz: Baz | |
} | |
struct Baz { | |
var value: String | |
} | |
let foo = Foo(bar: Bar(baz: Baz(value: "1")), baz: Baz(value: "2")) | |
print(foo) | |
let foo2 = foo.clone(with: | |
\.bar.baz.value.="3", | |
\.baz.value.="4" | |
) | |
print(foo2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment