O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Lens composition

Lens composition will help to simplify our lens; let's examine how:

infix operator >>> : AssociativityRight func >>><A, B, C>(l: Lens<A,B>, r: Lens<B, C>) -> Lens<A, C> {     return Lens(get: {                     r.get(l.get($0))                 },                 set: {                     (c, a) in                     l.set(r.set(c, l.get(a)), a)     }) } 

Let's test this:

let prodProducerAddress = prodProducerLens >>> producerAddressLens let mexBananaProducerAddress = prodProducerAddress.get(mexBananas3) let newProducer = prodProducerAddress.set("Acupulco, Mexico", mexBananas2) print(newProducer) 

The result is going to be as follows:

FunctionalProduct(name: "Banana",                   price: 0.79,                   quantity: 2,                   producer: Producer(name: "QAZ",                                      address: "Acupulco, Mexico")) 

Using lenses and composition, we were able to ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required