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.

ldiqual
  • 15,015
  • 6
  • 52
  • 90
  • 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](https://www.reddit.com/r/swift/comments/3a3k65/quick_tip_for_every_swift_programmer/) before, let me know if this answers your question and I will post this as an answer – Kametrixom Dec 12 '15 at 03:48
  • 1
    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` 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. – rickster Dec 13 '15 at 00:26

1 Answers1

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.

rickster
  • 124,678
  • 26
  • 272
  • 326