2

Case statements are not always intuitive, especially outside of switch statements.

Is it possible to return the associated value of an enum case only if that case matches, otherwise nil, in one line. Here's the code:

struct Something<B> {
    enum Base {
        case common(B)
        case extended([B])
    }

    let base:Base

    var common:B? {
        switch base {
        case .common(let common) :
            return common
        default:
            return nil
        }
    }
}

See how common has a lot of boilerplate just to return the associated value of common if it exists. I would hope for syntax similar to this (or even simpler):

var common:B? {
    return case base as .common(let common)
}

(currently using Swift 4)

Anh Pham
  • 2,108
  • 9
  • 18
  • 29
David James
  • 2,430
  • 1
  • 26
  • 35
  • Or something like this: `return (case .common(let common) = base)` which is still a bit verbose for what I'm trying to do. – David James Jul 10 '17 at 09:56

1 Answers1

2

This is a bit shorter

var common:B? {
    if case let .common(common) = base { return common }
    return nil
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • I'm afraid that's as good as it gets. Maybe I'll file an issue with the Swift team. – David James Jul 10 '17 at 10:43
  • @DavidJames - How much shorter would be clear and readable (like the elegance of that triple keyword run `if case let`)? Maybe something like `return case .common(common) ? common : nil` would suit you? It is almost Swift, and has a C-esque brevity. However Swift doesn't support pattern matching in the ternary operator (orthogonality be damned?), or omitting `let` (so you know its not `var`?). Maybe you should just accept the glory of the triple keyword? ;-) – CRD Jul 10 '17 at 20:46