[swift-evolution] [Pitch] Introducing the "Unwrap or Die" operator to the standard library
Erica Sadun
erica at ericasadun.com
Wed Jun 28 20:13:56 CDT 2017
> On Jun 28, 2017, at 6:26 PM, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
>
> On Wed, Jun 28, 2017 at 5:05 PM, ilya via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
> One could, for example, extend the existing documentation markup sign /// to pick up text as force unwrap messages:
>
> `let last = array.last! /// Array guaranteed non-empty`
>
> I did not call this out initially, but I feel like this is an important point to address:
>
> In the initial example, repeated here in largely identical form, the desired comment is "array must be non-empty." In what way does that provide more information than a bare `!`?
That is why I changed it back to my "guarantee" version when replying:
guard !array.isEmpty else { ... }
/* ... */
let finalElement = array.last !! "Array guaranteed non-empty"
The expected unwrap behavior is clear and audited, even when other code appears between the guard statement and the explained forced unwrap.
As you point out, it's senseless to annotate a logical assertion known to be true ("must be non-empty") unless that annotation enhances the expression of why and how this otherwise dangerous operation is taking place. That explanation forms the mission statement of the `!!` operator.
By explaining, the `!!` operator differs from the direct use of `!`. It explains a fact known to hold true that allows the lhs to safely unwrap. It provides this in a way that is succinct and readable. It naturally moves with the line of code it is part of. The adoption of `!!` has already broadly been integrated into any number idiomatic libraries. Coders have done so to differentiate an audited known fact from the stray `!`, which may or may not be followed by a comment.
One last point: it is not the mission of document comments to provide any role beyond annotation. They are not there to guarantee preconditions, assertions, or any other behavioral contracts. They merely document.
-- Erica
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170628/e7faa2fc/attachment.html>
More information about the swift-evolution
mailing list