Moving toward deprecating force unwrap from Swift?

Compiler flags like the ones suggested here, and warnings in general, have faced resistance in the past because the core team has wanted to avoid creating language dialects in Swift.

Later in that thread (which was about warnings in general, not force-unwrapping), @Joe_Groff calls out something that I think is especially relevant to this discussion:

In the case of force-unwrap, I don't think a fix-it/suggestion could cover all possible cases well and be useful to the user—it would be far too broad. And in many cases, if the user of the force-unwrap can guarantee that it won't trap due to other preconditions already known to hold, it may make more sense to just use ! and a suggestion to use if/guard let would harm the legibility of the code.

FWIW, I used to be fairly strongly on the side of "force-unwrap is a code smell", and when misused, it definitely is. But my experience has changed my mind to reinforce its legitimate uses as a language feature and that neither a compiler warning nor even a lint warning is something I'm comfortable with enforcing in my own code. (swift-format has rules to warn if force-unwrap/force-try are used, and we've turned them off by default because they were too noisy.) So I think if someone does want to enforce something stronger, enabling a linter in their own codebases is fine, but it's not something that the compiler should support or encourage.

17 Likes