> On 29 Jun 2017, at 11:18 am, Ben Cohen via swift-evolution > <[email protected]> wrote: > > >> On Jun 28, 2017, at 5:27 PM, Xiaodi Wu via swift-evolution >> <[email protected] <mailto:[email protected]>> wrote: >> >> 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 `!`? >> > > By the same token, why does precondition have an optional string? Why would > you ever want to write more than: > > precondition(!array.isEmpty) > > It’s self evident – the array must not be empty! Why the second argument? > > Because you might want a meaningful string to be output when the app traps. > And it gives you somewhere to document why it mustn’t be empty – the > explanation for the precondition rather than the precondition itself. > Similarly, when your app traps because of an unwrapped nil, it’s desirable to > get some output in your debug console telling you why straight away, rather > than have to hunt down the code, read the line that failed, then read the > context around the line, to understand the reason. This is even more > important if you didn’t write this code yourself. > > Finally, there’s a woolier justification: there’s an often-touted > misconception out there that force unwraps are bad, that they were only > created to accommodate legacy apps, and that force-unwrapping is always bad > and you should never do it. This isn’t true – there are many good reasons to > use force unwrap (though if you reaching for it constantly it’s a bad sign). > Force-unwrapping is often better than just whacking in a default value or > optional chaining when the presence of nil would indicate a serious failure. > Introduction of the `!!` operator could help endorse/encourage the use of > “thoughtful” force-unwrapping, which often comes with a comment of the > reasoning why it’s safe (of why the array can’t be empty at this point, not > just that it is empty). And if you’re going to write a comment, why not make > that comment useful for debugging at the same time.
I’m so glad the above has been stated outright here. It’s a bugbear of mine hearing people preach that the ! operator is always wrong. > > In cases where it’s really not necessary, ! would remain just like, when > you’re not really too fussed, you can leave off the string from a > precondition. > > > _______________________________________________ > swift-evolution mailing list > [email protected] > https://lists.swift.org/mailman/listinfo/swift-evolution
_______________________________________________ swift-evolution mailing list [email protected] https://lists.swift.org/mailman/listinfo/swift-evolution
