Optional Binding in Swift

Avoid those force unwraps

Steven Curtis
The Startup

--

Photo by Pierre Bamin on Unsplash

Often we want to avoid force unwrapping, and Optional Binding gives us a way of doing just that!

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE) or in Playgrounds (guide HERE)
  • Some knowledge of force unwrapping would be useful

Optional Binding

Optionals are a basic feature of Swift, and allow values to take either a value of .some or .none.

Crashing

This is great, but sometimes leads programmers to force unwrap an optional by using an exclaimation mark at the end of the variable.

So to get rid of the rather annoying Optional printout in the console, one might do the following:

var str: String? = "hello"
print (str!)

which is absolutely fine, since str is populated with the String “hello” in the first instance.

However, if we set the string to be nil we will view a rather nasty error:

var str: String? = nil
print (str!)

Which gives (with capitals) EXC_BAD_INSTRUCTION. Oh dear.

--

--