Enum Case KeyPaths

This is great! Thanks for your work on this so far @Alejandro!

As maintainers of CasePaths, @mbrandonw and I are definitely excited about any movement in this part of Swift, and we thought we would also be able to weigh in a bit on how case paths are used today.

The proposed getter functionality is definitely a step forward, but we wonder if it's possible to prioritize exposing the"embed" functionality in this pitch. We maintain a few popular projects that depend on the ability to embed values in enums abstractly, and they contain many real-world motivated uses:

  • swift-composable-architecture: An opinionated library for building/composing applications out of small units. Case paths are used in a few ways, but mostly to achieve this composition of features in a lightweight operation.

  • swiftui-navigation: A library that allows SwiftUI applications to model their navigation state in enums, which are a great data type for describing a list of destinations a view may navigate to. It uses case paths to derive SwiftUI bindings to these enum values held in state.

  • swift-parsing: A parsing library that can also generate a “printer” for “un-parsing,” or reversing a parsed output back into an input. Case paths are what power this bidirectionality for enums that appear in parsed output.

…and many third party dependencies that use CasePaths for both extract and embed functionality.

On top of the groundwork laid out so far, a new subclass in the key path hierarchy could potentially be introduced with the following functionality:

class CasePath<Root, Value>: KeyPath<Root, Value?> {
  func embed(_ value: Value) -> Root
}

With this in place, we could sunset our library, and downstream libraries could embrace native support, instead.

Also, one thing to note is that our library (and downstream libraries) can unfortunately not leverage any of the great work in this proposal so far. Today we resort to all kinds of runtime reflection in order to dynamically create case paths, and sadly there are still some edge cases that we have not yet figured out. But I don’t think we can replace any of that work with enum case key paths unless embed functionality is also exposed.

We’ve done a lot of thought in this problem space in Swift in general, so we are more than happy to collaborate further on various nitty-gritty details and future directions!

28 Likes