Straw Poll: Unwrapping solutions

Swift should be able to mitigate two issues related to forced unwrapping. First, it’s used as a bandaid by developers new to the language who want to make their code compile. Second, developers should be able to provide code-level annotation support for why a guaranteed wrap cannot fail and provide runtime diagnostics in any “Black Swan” scenario where they do. These items are discussed further in this proposal.

Please let me know which of the following designs you prefer. Each contains a link to a code solution. (The first item in the list (“Unwrap or Die”) links to a full proposal so scroll down to the design section.) The other two offer alternate designs. You can assume !! can be redesigned to support both throwing and Never solutions just as easily as fail or ??. The proposal goes into detail as to why that was not the original design, as doing so fundamentally changes nil-coalescing semantics.

Thank you in advance for your feedback and/or participation in the survey.

link to poll


  • I prefer “unwrap or die” above all because it’s the most concise and does what the program should do in most cases if the assertion fails: abort with a message explaining what the underlying assertion/assumption was or what invariant wasn’t met. Beginner users should be oriented to do exactly that in most cases.

    Swift errors are unlike exceptions and should be used relatively rarely for just assertions. When throwing an error is appropriate, a guard let is a simple and clear syntax.

    The third option (overloading ??) is less concise than “unwrap or die”. If fatalError isn’t the desired Never action, a guard let is sufficient for those cases. As for clarity, “unwrap or die” doesn’t overload an existing operator for seemingly different semantics whereas this option does, i.e., failing instead of providing a default value.

    I’ve been happily using !! in my codebases for over a year. It significantly improved understanding what my code does, even after several months of not reading it. I almost never use ! now. The extra keystrokes also act as a deterrent to use this escape hatch too often.

  • I have a couple of questions:

    1. Why am I returning an optional when I know beforehand that the wrapped value is always present?
    2. Are we trying to mitigate design errors with a language feature and do we really want to do that?

    IMHumbleO we should not give in to bad design by adding a language feature however it seems that currently everybody is retrofitting Swift with their own extension. In that case, would a lambda instead of an error string be better so that:

    wrapped !! die()
    wrapped !! exit()
    wrapped !! log_and_complain()

    be desirable?