Swift Delight: No Unused Results
Swift delight: no unused results by default. That is, when you call a function in Swift, you get a warning if you don’t use (or explicitly discard) the result.
— Jordan Rose (@UINT_MIN) November 30, 2021
Part of the Swift Regrets series.
Unused result checking has been an opt-in check in one form or another in a lot of imperative languages. Sometimes it’s a style-guide-driven linter that checks call sites. Sometimes it’s an attribute on the function declaration. “This result is important!” There’s even an extension of that where the attribute goes on a type, and whenever that type is returned it has to be used. Thinking about it now, though, that’s just a hack. It’s not really about the type; it’s that most operations that use that type want the stricter rules.
Swift does away with all this approximation by requiring that every result be handled (with the exception of Void, Optional<Void>
, and “uninhabited” types like Never, and maybe a few others I’ve forgotten).
And then, because of side effects, there are some functions where the result is secondary. Removing from a dictionary is a good example: sometimes you want to use the just-removed value, but usually you don’t need it anymore. So there’s the discardableResult
attribute.
This wasn’t in the first version of the language! But now I’d never want to go back, and miss it in other languages. Thanks, Erica Sadun and Adrian Kashivskyy.