Wednesday, October 8, 2014

Make a Swift Based iOS App Crash

I am writing an app for a contract where one of the deliverables is that the app must demonstrate various crashes.  Of these various crashes, one must be an application crash.

On top of that I am writing the app in Swift (about 80% Swift, 20% Objective-C libraries not ported to Swift).

It shouldn't be too hard to crash a Swift app hey? Well, if you follow Swift guidelines your app should be pretty stable since the language has been designed to force devs to be safer in their use of the language. That's not to say that misunderstanding the language or forced unwrapping of optionals that could be nil will make your app any less crash prone.

So let's break the rules, get unsafe in our use of Swift and crash this app.

I decided to go with this piece of code:
var crashWithMissingValueInDicitonary = Dictionary<Int,Int>()
let crashInt = crashWithMissingValueInDicitonary[1]!
This produces a crash with the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
The reason is this:

  • Line 1 is creating an empty dictionary with Int keys and Int values.
  • Line 2 is Force Unwrapping the optional dictionary value with a key of 1. Nothing has been added to our dictionary yet though so this means we will get a nil. Assigning this nil to a constant value (let) and we get a runtime exception, crashing the app.
So, there is one way to write a bug intentionally to crash your app.

No comments: