Never listen to Xcode regarding optionals.

If you don’t know what optionals are or are confused on the topic, check out my last post.

I’ve noticed a lot of beginners do this so I thought I’d write about it.

When working with optionals, Xcode usually suggests you to unwrap an optional by adding a !.

If you do this without knowing 100% that variable/constant has a value, your screwing yourself in the ass.

Sure you can put a ! just as Xcode suggests to get rid of the error, but only in runtime your application may crash.

Let’s open playground and try this out.

Type this line of code. It’s a simple, variable with optional string.

var str: String? = “someString”

Without knowing how to properly unwrap optionals to print() this, a beginner programmer would do something like this because Xcode suggests this as fix.

Face value this works but you may encounter problems later on.

Now pretend this str variable was for entering an email and the user didn’t enter it, but your trying to force unwrap it. It’s going to crash.

You’ll get an error like this:

fatal error: unexpectedly found nil while unwrapping an Optional value

Here’s a list of ways you could have unwrapped it safely instead.

Hope that helps!

I uploaded the playground file to my GitHub if you get stuck or need to check your code.

If you have any questions or suggestions on what you’d like to see please let me know! 😀