Programming in Swift: Fundamentals

Oct 19 2021 Swift 5.5, iOS 15, Xcode 13

Part 1: Core Concepts

8. Challenge: Optionals

Episode complete

Play next episode

Save for later
About this episode
See versions

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 7. Optionals Next episode: 9. Conclusion

Update Notes: The student materials have been reviewed and are updated as of October 2021.

It’s time for your next challenge! You can find the challenge in the “Challenge - Optionals” page of the playground you’ve been using, or you can download a new one from the resources for this video. Open it up, and try solving the challenge questions on your own, then keep watching to compare your work to ours. Good luck!

You’ve been provided with a constant below, hasAllergies, which has been set to true. Below that, declare a Optional String variable named dogName. On the next line, use a ternary conditional operator to set the value of dogName to nil if hasAllergies is true, and to "Mango" otherwise.

First, I declare the constant and set it to true:

let hasAllergies = true

Then, I declare a variable dogName, and set it as an optional String:

var dogName: String?

Next, I use a ternary conditional operator to say dogName is, depending on the value of hasAllergies, nil, if true, and otherwise, Mango:

dogName = hasAllergies ? nil : "Mango"

Create a constant named parsedInt and set it to Int("10"). Swift will attempt to parse the string 10 and convert it to an Int. Place your mouse over the constant name and use Option-Click to check the type of parsedInt. Why is parsedInt an optional here?

First, declare the constant and set it to Int(“10”), where ten is in quotes, to tell Swift to treat this as a String.

let parsedInt = Int("10")

Why is parsedInt an Optional in this case? You and I both know that “10” as a String will easily convert to an Integer.

But Swift won’t know this until it actually does the hard work of figuring out if it can convert this string value to an integer.

So, to be safe, Swift implicitly creates parsedInt as an Optional - just in case it can’t convert what’s inside the String.

That’s the end of this challenge — I have a short conclusion video for you next to help you wrap up this part of the course and introduce you to what’s next!