I personally think this is an interesting syntax to extract enum payloads.
To correctly infer the right payload-tuple type, the enum case needs to be passed in some way. You suggested to use myEnumInstance[keyPath: \.myCase]!
to access the associated values, but that would require your Enum to conform to a new protocol for API stability.
On the other hand, as? case
or as! case
would work without new requirements.
I'm interested in having analogies between enums and optionals (which are enums):
let a: Int? = 3
// unwrap value in an optional
if let a = a { ... }
if let a = a as? Int { ... }
// force unwrap value in an optional
let b = a!
let b = a as! Int
// unwrap values in an enum
if case let .some(x) = a { ... }
if let x = a as? case .some { ... } // new syntax, x is Int
// force unwrap values in an enum
let x = a as! case .some // new syntax, x is Int
Enum force unwrapping would then be chainable as optional force unwrapping:
enum Enum1 { case .foo(Int, String) }
enum Enum2 { case .bar(Enum1) }
let a: Enum2 = .bar(.foo(3, "three") }
let (num, string) = (a as! case .bar) as! case .foo // num is Int, string is String