[Pitch] Add dynamic member lookup to `Result`

Result hasn't been touched too much since it was added to the standard library, but in the initial pitch thread, a lot of people wanted optional chaining for it. We could add dynamic member lookup to produce a similar effect.

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

  // ...

  subscript<Property>(dynamicMember: KeyPath<Success, Property>) -> Result<Property, Failure> {
    switch self {
      case .success(let success): return success[keyPath: keyPath]
      case .failure(let failure): return .failure(failure)

This could be used like this.

func makePerson(_ completionHandler: (Result<Person, Error>) -> Void) { ... }

makePerson { result in 
  try print(result.name.get())

Does the community think this would be useful?


We can already do this:

makePerson { result in 
  try print(result.get().name)

is there some other expressive benefit that would be brought by your suggestion that I'm not seeing?

1 Like

The other spelling for that we already have to today is:

1 Like

Well, let's see:

struct Person {
  var name: String
  var age: Int

  struct Disease: Error { }

// with optionals
let person: Person? = nil
print(person?.name) /* of type String? */

// with results currently
let person: Result<Person, any Error> = .failure(Person.Disease())
print(person.map { $0.name }) /* of type Result<String, any Error> */

// with results with this proposal
let person: Result<Person, any Error> = .failure(Person.Disease())
print(person.name) /* of type Result<String, any Error> */

So it doesn't provide that much additional functionality, but it does add more consistency with optionals.

Result was a bare bones type because it was felt (by others, not myself as proposal author) that things like associated value accessors, subscripts, or other convenience API should be implemented as general enum features rather than anything specific to Result. This continues to be the case. With the arrival of macros, many of the features desired, like associated value accessors, can be generated by macros instead. So it's unlikely there's any desire to add these features to enums, much less Result in particular.


I feel like dynamic member lookup could be extended to allow "member lookup operators", which are like normal operators except the right hand side is a key path. This way "?" could be defined for user code, and the same or similar operators can be added to Result, Array, etc.