SE-0217 - The "Unwrap or Die" operator

The use case for this feature is basically "I want to force-unwrap a value, but I am a mere mortal who is sometimes confused about my preconditions". In other words, the use case for this feature is basically "I want to force-unwrap a value".

But let's focus on one specific sub-case: users who don't really understand optionals yet. I find this Stack Overflow question instructive on the question of whether developers are currently understanding force-unwraps. This error message only comes up when you either force-unwrap incorrectly, or when you access an IUO when you shouldn't, and a developer who understands these features should not need to look up the message. Thus, traffic on this question may be a good proxy for confusion about force-unwrapping and/or IUOs.

As I write this, the question has 216,821 views, 281 upvotes (meaning users thought the question itself was a good one), and 134 favorites (meaning users bookmarked it for later reference). The top answer has 497 upvotes and has been opened to community editing so it can serve as an authoritative source. These are all huge numbers, akin to, for instance, the question about EXC_BAD_ACCESS in Objective-C. Taken together, these numbers suggest to me that users frequently force-unwrap inappropriately and struggle to understand what went wrong.

Moreover, they continue to struggle. I went back and looked at this question in the Wayback Machine so I could chart its activity over time:

Unwrap%20stack%20overflow

It doesn't look like people are getting much less confused about when to force unwrap.

To me, the crucial part of this proposal is that it modifies the fix-it on optional misuse, replacing the "Insert '!'" fix-it with a pair which insert either ?? or !!. I think this would help users who don't understand optionals yet in three ways:

  1. It would offer an option besides force unwrapping, so users would be aware that there were other ways to fix the issue.
  2. It would replace the force-unwrap fix-it with one which requires more thought to use (you have to fill in the placeholder for the right-hand side), so you're less tempted to "just make it work" by choosing that option.
  3. The placeholder's wording implies that you should only use !! when you're certain the value can't be nil, so some users may figure out that it's not the construct they need.

Without !!, we could still change the fix-it to suggest ?? or ! as alternatives. But inserting ! would still be the easier fix, and there would still be nothing to make it obvious that this might not be the right thing to do.

Maybe this isn't the right solution. But it's hard for me to see this use-case as having "dubious value" when 5,700 people have struggled with the status quo in the last three weeks.

(P.S. It looks like @jtbandes has been moderating this Stack Overflow question and making sure it remains helpful for confused Swift users. Thank you!)

9 Likes