Member-only story

Swift Programming Tutorial: if let statement

Understand the if let Statement in Just a Few Minutes

--

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, and we can safely use actualName because we know it’s not empty.
  • If name is nil (empty), the else 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.

--

--

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

Write a response