Issue #528
What is lense
A lens is a first-class reference to a subpart of some data type. For instance, we have _1 which is the lens that “focuses on” the first element of a pair. Given a lens there are essentially three things you might want to do
View the subpart Modify the whole by changing the subpart Combine this lens with another lens to look even deeper
Before, use functional approach
http://chris.eidhof.nl/post/lenses-in-swift/
struct Person {
let name_ : String
let address_ : Address
}
struct Address {
let street_ : String
let city_ : String
}
struct Lens<A,B> {
let from : A -> B
let to : (B, A) -> A
}
let address : Lens<Person,Address> = Lens(from: { $0.address_ }, to: {
Person(name_: $1.name_, address_: $0)
})
let street : Lens<Address,String> = Lens(from: { $0.street_ }, to: {
Address(street_: $0, city_: $1.city_)
})
let newAddress = street.to("My new street name", existingAddress)
Now, with Keypath
https://iankeen.tech/2018/06/05/type-safe-temporary-models/ https://swiftbysundell.com/articles/defining-testing-data-in-swift/
Use KeyPath to modify struct data
protocol Stubbable: Identifiable {
static func stub(withID id: Identifier<Self>) -> Self
}
extension Stubbable {
func setting<T>(_ keyPath: WritableKeyPath<Self, T>,
to value: T) -> Self {
var stub = self
stub[keyPath: keyPath] = value
return stub
}
}