Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How do I avoid Force Unwrapping my code?

I am trying to create a simple coin flip app but it will only work if I force unwrap imagines that I'm trying to include:

import GameKit

struct FlipResultModel {

let flipResult = [UIImage(named: "quarterHeads.png"), UIImage(named: "quarterTails.png")
]
func getRandomFlipResult() -> UIImage {
    let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(flipResult.count)
    return flipResult[randomNumber]!

}

}

I created this before learning about optionals and I can't figure out how NOT to force unwrap "return flipResult[randomNumber]!".

2 Answers

Since you know those images will be there you won't run the risk of a crash. This was strictly from playground but it didn't have an error.

let flipResult = [UIImage(named: "quarterHeads.png"), UIImage(named: "quarterTails.png") ] 
func getRandomFlipResult() -> UIImage? { 
    let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(flipResult.count)
    return flipResult[randomNumber]

}

Thanks for the help, I messed around with this for hours and thought I had tried everything!

Nathan Tallack
Nathan Tallack
22,164 Points

First of all, don't force unwrap like that. That's bad, mkay! You are getting an optional when using UIImage because there is a chance that the image you are reading in cannot be read in for plenty of reasons.

What you should do is pass the optional and deal with it as an optional. That is the safety of the optional. So you don't have your app unexpectedly crash if for some reason the image did not load.

So, where you are using your function, expect an optional UIImage returned, safely handle it so that if it is a None value you either log the output for debug or pop up an apology dialog to the user, or both.

It is extra work, I know. But it is very very imporant that you embrace the purpose of the optional to write safer code. :)

Remember, force unwrapping is bad mkay! ;)