Swift Programming Tutorial: if let statement
Understand the if let Statement in Just a Few Minutes
4 min readOct 19, 2024
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…