Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to detect forced unwrapping across a Swift project?

Is there a way (via a compiler flag or a script) to detect forced unwraps across a Swift project?

I'm thinking about stuff like these:

let b = a as! B
let c = a!
a!.method()

Without triggering false-positives for var a: A! for instance.

like image 980
ldiqual Avatar asked Dec 12 '15 02:12

ldiqual


1 Answers

As noted in comments, a regex search can be crafted to catch most uses of postfix !. (And if you're careful, you should be able to make it ignore most uses of colon-typename-bang so you don't get noise from IUO type declarations.)

This is about as good as it gets, though, and it's incomplete — for example, any time you call an API that returns an IUO type and access its result without checking the optional, you could be doing a force-unwrap without explicitly having any bangs in your code.

Any tool that attempts to warn about unchecked unwraps consistently would need to have a pretty deep knowledge of Swift's type system, grammar, and type inference rules. And really the only place you can have such knowledge (and have it correctly) is inside the compiler. So you're probably best off filing a feature request to Apple or working with the open source project.

like image 99
rickster Avatar answered Nov 08 '22 20:11

rickster