bow-swift / bow

🏹 Bow is a cross-platform library for Typed Functional Programming in Swift
https://bow-swift.io
Other
643 stars 32 forks source link

Question: How to connect Lens which has optional value? #656

Closed haifengkao closed 3 years ago

haifengkao commented 3 years ago

suppose I have the following structures:

struct Handle: AutoLens  {
}

struct Door: AutoLens  {
   var handle: Handle?
}

struct Car: AutoLens {
    var door: Door?
}

I can use Car.lens(for: \.door) to get Lens<Car, Door?> Door.lens(for: \.handle) to get Lens<Door, Handle?>

but when I connect the two Car.lens(for: \.door) + Door.lens(for: \.handle) the compiler will tell me type mismatch

How do I connect these lens?

truizlop commented 3 years ago

When you have a field that has an optional type, there is an optic to address this fact. You can look for Optional (in the last released version), which has been renamed to AffineTraversal in the next release we will do.

You can check the documentation of how to write your own AffineTraversal/Optional and [how to get it automatically]. Also, we have documented its API.

In your particular example, and using Bow 0.8.0, it would be something like:

struct Handle: AutoOptional  {}

struct Door: AutoOptional {
   var handle: Handle?
}

struct Car: AutoOptional {
    var door: Door?
}

Car.optional(for: \.door) + Door.optional(for: \handle)
haifengkao commented 3 years ago

thanks 😘