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

1

7

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.

Galactometer answered 12/12, 2015 at 2:57 Comment(2)
You can regex search "[^\1]![\s\p{P}]" to find such instances including implicitly unwrapped optionals (using them is usually as bad as forced unwrapping) excluding the prefix ! operator for Bools and similar. I posted this here before, let me know if this answers your question and I will post this as an answerWolford
Using the force unwrap operator, the force cast operator (as!), or the ignore error statement (try!) isn't an unconditionally, universally bad thing. Likewise use of the ImplicitlyUnwrappedOptional<T> type -- all of these are constructs that can be used safely, with careful consideration, or used thoughtlessly in ways that can introduce bugs. I'd grant that the former three are more likely a sign of careless coding than use of the IUO type, though, especially considering that IUOs are necessary (and recommended) for use cases like IB outlets.Fructificative
F
1

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.

Fructificative answered 13/12, 2015 at 0:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.