Introducing `Unwrappable`, a biased unwrapping protocol

I like some of the ideas here, but I don't like the dilution of ?.

  • Types: Int? means Optional<Int> (Optional)

  • Chaining: foo?.bar means what foo.unwrap()?.bar means today (Unwrappable)

  • Coalescing: foo ?? bar means…well, I'm not sure, actually. That needs to go into the proposal specifically if you want to extend it to Unwrappable. (I'm particularly concerned about the form that takes two Optionals, not the one that takes an Optional and an Element.)

  • Pattern-matching: case let foo?: could mean Unwrappable, but then you'd still get diagnostics about not handling all cases, because the compiler can't tell how unwrap() maps to cases.

  • try?: still produces an Optional (also kind of an anti-pattern anyway)

  • init?: still produces an Optional

  • Ternary operator: a ? b : c has nothing to do with Optional or Unwrappable (included for completeness and because I think "Replace ternary _ ? _ : _ operator with a binary _ ? _ operator" is clever but not something we'll actually do)

So in the end, the only feature with ? in it that clearly and easily benefits from this is chaining. It also benefits if let and guard let. I'm not sure those justify the proposal, especially when it's not really that bad to call .unwrap() explicitly or use a higher-order function (think flatMap or ifSuccess).

I do appreciate having this written out! I don't think I would have been able to consider the tradeoffs otherwise.

12 Likes