UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 14 Option chaining review question #12

Forums > 100 Days of SwiftUI

I've realized am not grasping optional chaining very well.

let racers = ["Hamilton", "Verstappen", "Vettel"]
let winnerWasVE = racers.first?.hasPrefix("Ve")

My initial thoughts were that racers.first cannot be nil since racers is an array with elements in it. I concluded the question mark was not needed. This isn't true clearly since the answer is True. What makes racers.first an optional?

2      

What should be returned if an array is empty? Since that is a possibility, Array.first returns an Optional.

Just because this particular instance of an array happens to be empty doesn't change things.

2      

dee isn't grepping the chain:

I've realized am not grasping optional chaining very well.

let racers      = ["Hamilton", "Verstappen", "Vettel"]  // Clearly this array has values.
let winnerWasVE = racers.first?.hasPrefix("Ve")         // Why? Why the question mark?

You and I can clearly see that racers array has three strings in it.

But the method first is less sure. It has to work with all kinds of arrays. Arrays with one value, arrays with thousands of values, and empty arrays. As @rooster points out, what should get returned if the racers array is empty?

If you're absolutely, 100% sure the array has values, you can force unwrap the array with the bang (!) character. But, of course, if the array somehow loses all its values, this line will crash your program.

let racers      = ["Hamilton", "Verstappen", "Vettel"]
let winnerWasVE = racers.first!.hasPrefix("Ve")  // <-- force unwrap

If you look at the definition of the first method in the documentation, you'll see that first returns an optional. It doesn't return a string, or an integer, or a double. It returns an optional.

Also take note! The chain racers.first?.hasPrefix("Ve") will fail if first return nil.
So what is the value of winnerWasVE ? It will also be nil!
Remember that winnerWasVE is NOT a bool. It is an optional bool.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.