Skip to content

Instantly share code, notes, and snippets.

@glukianets
Created August 23, 2021 18:21
Show Gist options
  • Save glukianets/e3ee27395af05e4edf86aaed0926c71c to your computer and use it in GitHub Desktop.
Save glukianets/e3ee27395af05e4edf86aaed0926c71c to your computer and use it in GitHub Desktop.
Poor man's lenses in swift
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