The Swift Programming Language Companion: Optionals

loufranco profile image Lou Franco Updated on ・3 min read

This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple.

The Swift Programming Language Companion Recap


We set up a reading environment that will let you write code as you read. For The Swift Programming Language, we are using an Xcode Playground.

The Basics

Next, we picked some app idea (in my case a workout app for the Apple Watch). This app is what we are going to use to change all of the code examples in the book to examples we generate based on our app. If you don't have a app idea, just pick any app you use a lot. The important part is that it will help us new code samples.

Another important lesson is that we learned how to describe code with words. This is important, because as we progress I am going to use regular sentences that I think you should be able to translate to code based on where we are in the book.

At this point, you should have read The Basics in The Swift Programming Language. You should have a Playground page for this chapter with code in it that you generated while reading the book.

Exercises for The Basics

We are going to base all of these examples on an app that tracks what you eat. Each exercise is new lines of code.

  1. Declare a constant named appleCalories and set it to 50
  2. Declare a variable named caloriesEatenToday and set it to 850
  3. Declare a String variable named food with no initial value
  4. Set food equal to "banana"
  5. Make a comment that says "Here is a list of food"
  6. Under the comment, declare three constants named food1, food2, and food3 and set them to names of different food (Strings)
  7. Declare a constant named bananaCalories and set it to any floating-point number
  8. Declare a variable named eatenEnoughToday and set to a Boolean constant (true or false)
  9. Write an if-else statement that checks eatenEnoughToday and prints "Great!" if it's true and "Eat more" if it's false.
  10. Make some examples based on this app for the sections we didn't cover in these exercises. Especially if you didn't understand them (or ask me for help in the comments).

If you want, message me your Playground Page for feedback.


So, I wanted to talk about Optionals separately, but instead of explaining them, I'd like these posts to be a true "Companion" and go through the text of the book itself.

You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.

So, a Bool represents true or false, but a variable of the optional type Bool? could be nil as well, which means that the variable doesn't have a value at all.

The example given a function that converts String values into Int. If a string value were "14", then the function could return 14. But, what should it do if the string is "Hello". By using Int?, it can return nil in this circumstance.

Avoid the ! operators for any real code

The next section introduces the ! operator for optionals. When appended it to a variable, it "force unwraps". So, if it's not nil, great, it gets the value. But, if it is nil, your app crashes. It's fine to use in a Playground, but when you get to real code, avoid it until you really understand how to use it safely (yes, there are times it's safe). Similarly, avoid appending it to type annotations to create "Implicitly unwrapped" variables.

Many Swift developers call these operators the "crash operators". Their original name, the "bang operator", is no less ominous.

Instead, understand if-let, guard-let and the safe unwrapping operators (? and ??)

Here is the if-let example from the book:

You can rewrite the possibleNumber example from the Optionals section to use optional binding rather than forced unwrapping:

if let actualNumber = Int(possibleNumber) {
    print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
    print("The string \"\(possibleNumber)\" could not be converted to an integer")

Play around with this code in the Playground, creating a variable called possibleNumber just before this code and setting it to various strings (e.g. "123", "hello", etc)

What's next?

Next, we'll move onto Basic Operators. Read (and write code to) it now and I'll go over it in the next post.

Posted on by:

loufranco profile

Lou Franco


Software Engineer on Trello iOS for Atlassian.


markdown guide