[swift-evolution] Pitch: Even Smarter KeyPaths?

Stephen Celis stephen.celis at gmail.com
Mon May 15 10:29:09 CDT 2017


I've started to explore Smart KeyPaths in the latest Swift Development Snapshot with regard to lenses and have been pleasantly surprised: Swift has one of the better out-of-box optics stories I've come across!

In (brief) use I've come across a few gaps that I was hoping we could fill in.

## Tuple KeyPaths

I hoped these would work already, but I hit a compiler crash: https://bugs.swift.org/browse/SR-4888

```
struct Location {
  let coords: (lat: Double, lng: Double)
}

\Location.coords.lat
\Location.coords.0
```

## Enumeration KeyPaths

I tried to find discussion around enum KeyPaths but couldn't find any.

```
struct User {
  let name: String
}

enum Result<Success, Failure: Error> {
  case success(Success)
  case failure(Failure)
}

\Result<User, Error>.success?.name
```

Enumeration cases with multiple values could use tuple-style matching.

```
enum Color {
  case gray(Double, a: Double)
  case rgba(r: Double, g: Double, b: Double, a: Double)
  // ...
}

\Color.gray.0?.description
\Color.rgba.r?.description
```

## Other Ideas

The above are just quick ideas that would partially cover more use cases of lenses and prisms, but I'd love to explore other optics, as well. E.g, traversals: `\User.friends[..].friends` to return a user's friends' friends.

-
Stephen



More information about the swift-evolution mailing list