Swift Programming Tutorial: if let statement

Understand the if let Statement in Just a Few Minutes

Arc Sosangyo
4 min readOct 19, 2024
Photo by Kira auf der Heide on Unsplash

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 in name. If there is, it unwraps it and gives it to the new constant actualName.
  • If name is not nil, the code inside the if block runs…

--

--

Arc Sosangyo
Arc Sosangyo

Written by Arc Sosangyo

Arc is an iOS Dev and app publisher, a former IT manager who transitioned to iOS engineering, and a big fan of AI, coding, science, history, and philosophy.

No responses yet