How to do lense in Swift

Issue #528

What is lense

https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/a-little-lens-starter-tutorial

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/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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

1
2
3
4
5
6
7
8
9
10
11
12
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
}
}

Comments