Member-only story
Swift Programming Tutorial: if let statement
Understand the if let Statement in Just a Few Minutes
If this is your first time learning Swift programming, make sure you understand the concepts of optionals and conditional statements.
In Swift, sometimes you’ll have variables that might have a value, but might also be empty (this is called an optional).
Here’s a quick example:
var name: String? = "Arc"
if let actualName = name {
print("Hello, \(actualName)!")
} else {
print("No name found.")
}
Here’s the output:
Hello, Arc!
Now let’s try not assigning a value to the optional variable.
var name: String?
if let actualName = name {
print("Hello, \(actualName)!")
} else {
print("No name found.")
}
Here’s the output:
No name found.
What’s happening here?
name
is an optional variable. It might have a string like "Arc", or it might be empty (nil).- The
if let
statement checks if there’s a value inname
. If there is, it unwraps it and gives it to the new constantactualName
. - If
name
is not nil, the code inside theif
block runs, and we can safely useactualName
because we know it’s not empty. - If
name
is nil (empty), theelse
block runs instead.
Does that make sense?
This article is part of my Swift Programming Tutorial series.
Why do we even need if let
?
In Swift, not every variable has a value 100% of the time. Some things might be optional, meaning they could either hold a value (like a string, a number, etc.) or be empty (which in programming we call nil
).
Imagine you’re working with someone’s phone number. Sometimes people have a phone number, and sometimes they don’t. You don’t want your app to crash if you try to use a phone number that doesn’t exist, right? That’s why we use optionals — they allow us to represent the possibility that a value could be missing.