Menu
Coddy logo textTech

Unwrapping With If Let

Part of the Fundamentals section of Coddy's Swift journey — lesson 12 of 86.

To safely access the value inside an optional, we use if let — a technique called optional binding. This checks if the optional contains a value and, if so, unwraps it into a temporary constant.

var username: String? = "Swift_Dev"

if let name = username {
    print("Welcome, \(name)")
} else {
    print("No username found")
}
// Welcome, Swift_Dev

Here, if let checks whether username has a value. Since it does, the value is unwrapped into name, which exists only inside the if block. If username were nil, the else block would run instead.

var age: Int? = nil

if let unwrappedAge = age {
    print("Age is \(unwrappedAge)")
} else {
    print("Age not provided")
}
// Age not provided

Since age is nil, the condition fails and the else block executes. This prevents crashes that would occur if we tried to use a missing value directly.

challenge icon

Challenge

Easy

You are provided with the following variable:

var nickname: String? = "CoddyLearner"

Use if let to safely unwrap nickname. If it contains a value, print Hello, [value]! where [value] is the unwrapped nickname. If it's nil, print No nickname set.

Cheat sheet

Use if let (optional binding) to safely unwrap an optional and access its value:

var username: String? = "Swift_Dev"

if let name = username {
    print("Welcome, \(name)")
} else {
    print("No username found")
}
// Welcome, Swift_Dev

If the optional contains a value, it's unwrapped into a temporary constant that exists only inside the if block. If the optional is nil, the else block executes:

var age: Int? = nil

if let unwrappedAge = age {
    print("Age is \(unwrappedAge)")
} else {
    print("Age not provided")
}
// Age not provided

Try it yourself

var nickname: String? = "CoddyLearner"

// TODO: Write your code below
// Use if let to safely unwrap nickname
// If it contains a value, print "Hello, [value]!"
// If it's nil, print "No nickname set"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals