Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Control Structures and Optionals in Swift (Part I)

DZone's Guide to

Control Structures and Optionals in Swift (Part I)

Follow along and learn how to access an Optionals value in four different ways over this two-part series.

· Mobile Zone
Free Resource

Optionals in Swift take a bit of getting used to, but once you start to use them, two things seem to happen. First, you stop using them in your own code, and you get annoyed whenever you need to deal with them (I’m looking at you, UIKit). And second, you discover all the different ways you can pull values from them, and realize you don’t really know when to use what.

Well, I’m going to help you with that today. You’re welcome!

Four Ways to Skin an Optional

So, in the latest version of Swift, we have four different ways we can access an Optional’s value. We can use ?, !, if let..., and guard.... Today we're going to cover the first two, and in Part II we'll cover the last two and wrap up.

Bang!

! is pretty simple: only use this when you absolutely know that the Optional contains a value.

You should really only use this when you have code something like this:

var myval: String?
myval = "This is crazy pedantic"
print("I know, right! \(myval!).")


Here we absolutely know that the Optional has a value and is not nil. If it was nil, oh noes!

fatal error: unexpectedly found nil while unwrapping an Optional value

That’s what you get. So don’t bang an Optional unless you absolutely know it’s safe.

Say What?

The next three are where things start to get confusing - especially with ? and if let .... So let’s look at them first.

First, here’s something you can do with if let... that you can’t do with ?:

if let myVal = anotherVal {
print("\(myVal)")
}


If you try to print using ?...

print("\(anotherVal?)")


The Swift compiler calls you a chump:

error: '?' must be followed by a call, member lookup, or subscript

Why is this? Well, the ?’operator is for optional chaining, not optional calling. So, with optional chaining, you can call member functions of an Optional, and if the optional is nil, the calls will short-circuit to a nil value. This can be useful in some cases, sure, but it causes Optional types to propagate throughout your code.

If I do this, for example:

struct StringStruct {
var value: String
}

var strStruct: StringStruct?
strStruct = StringStruct(value: "test")
var someValue = strStruct?.value
print("\(someValue)")


Take a look at the bottom gutter in playground; the final print statement emits Optional("test"). This is because using the ? operator for optional chaining may return a nil value, so anywhere you assign a value from optional chaining, the assigned type must be optional.

Here’s my take on this. The designers of the Swift language went to great lengths to avoid nullable values by creating a special type for these cases. They did this because null pointers are traditionally the bane of any program, including Swift programs. Avoiding nullable types if you can will lead to safer code as it shrinks your error surface. This is a good thing. I try to follow the spirit of the original language designers and avoid nullable types by limiting my use of optionals as much as I can. I suggest you do to, and limit your use of optional chaining.

Thanks for making it this far. In Part II, we'll discuss guard statements and more complex optional control structures.

Topics:
swift ,control ,optionals

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}