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

Lenses

In the previous section, we covered copy constructors. Here, we will examine a functional structure called a lens. Simply put, lenses are functional getters and setters that are implemented for a whole object and its parts:

  • Getters: We can look through the lens at an immutable object to get its parts
  • Setters: We can use the lens to change a part of an immutable object

Let's implement a lens:

struct Lens<Whole, Part> {     let get: (Whole) -> Part     let set: (Part, Whole) -> Whole } 

Let's use it to change our FunctionalProduct object to get and set the producer property:

let prodProducerLens: Lens<FunctionalProduct, Producer> =     Lens(get: { $0.producer },          set: {              FunctionalProduct(name: $1.name,                                price: $1.price,     quantity: $1.quantity, ...

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