[swift-evolution] [Pitch] Introducing the "Unwrap or Die" operator to the standard library
cantrell at pobox.com
Wed Jun 28 20:58:35 CDT 2017
> On Jun 28, 2017, at 8:32 PM, Xiaodi Wu via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
> I would like to see an example where this string plausibly makes the difference between having to hunt down the code and not have to do so. I do not believe that "array must not be empty" or "array guaranteed non-empty" is such an example, and I cannot myself imagine another scenario where it would make such a difference.
You needn’t imagine. There was one up-thread:
let paramData = params.data(using: String.Encoding.ascii)!
Huh? Why is force unwrap safe here? OK, the code plainly says the author thinks that `params` must already be ASCII, but why is that a safe assumption? What reasoning lead to that? What other sections of the code does that reasoning depend on? If we get a crash on this line of code, what chain of assumptions should we follow to discover the change that broke the original author’s reasoning behind the force unwrap?
This is a job for a comment:
let paramData = params.data(using: String.Encoding.ascii)! // params is URL-escaped, thus already ASCII
Aha, it’s URL escaped.
That comment does not repeat information already stated in the code itself. It does what any good comment does: it explains intent, context, and rationale. It doesn’t restate _what_, but rather explains _why_.
For those who appreciate comments like that, this proposal simply allows them to surface at runtime:
let paramData = params.data(using: String.Encoding.ascii) !! "params is URL-escaped, thus already ASCII"
And those who see no value in such a runtime message — and thus likely also see no value such a comment — are free not to use either.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-evolution