From the course: Swift 5 Essential Training
Unlock the full course today
Join today to access over 24,100 courses taught by industry experts.
Unwrapping optionals - Swift Tutorial
From the course: Swift 5 Essential Training
Unwrapping optionals
- [Instructor] Now that we've seen if statement syntax, we can talk about handling optionals the correct way with optional binding. Essentially, we use a variation of the if statement to safely unwrap the optional, whether it's a value or nil, and then store it locally for use. I've already created a few optional values that we've used in earlier sections, so that we can get right to work here. For our first example, we're going to unwrap item gathered. So here we use the if keyword and then let, and here we have to declare the name of the locally unwrapped optional. So we'll call that item, and it's going to be equal to item gathered, followed by an open and closed curly braces. Now in plain English, we're saying, if item gathered is not nil, unwrap the value and assign it to item, which we can then use in the body of the if statement. So we could print out an interpolated string here, you found an item. I'm going to…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
-
(Locked)
Controlling your destiny27s
-
(Locked)
The if statement3m 44s
-
(Locked)
Unwrapping optionals5m 22s
-
(Locked)
Using for-in loops7m 16s
-
(Locked)
While loops2m 54s
-
(Locked)
The switch statement6m 59s
-
(Locked)
The guard statement3m 22s
-
(Locked)
Challenge: Game logic37s
-
(Locked)
Solution: Game logic5m 33s
-
(Locked)
-
-
-
-