Ahmet Balaman LogoAhmet Balaman

Introduction to Swift: Optionals, Guard Let and If Let Usage

personAhmet Balaman
calendar_today
SwiftiOSOptionalsGuard LetSwiftUI

Introduction to Swift: Optionals and Safe Unwrapping

Hello! After learning mobile app development with Flutter, I decided to learn Swift for iOS-specific applications. On my first day, the topic that confused me the most but is also one of Swift's best features was Optionals.

What is an Optional?

In Swift, a variable either contains a value or contains nothing. nil is used to express this "nothing" state. However, for a variable to be nil in Swift, it must be defined as Optional.

// Normal String - cannot be nil
var name: String = "Ahmet"

// Optional String - can be nil
var surname: String? = nil
surname = "Balaman"

Just like we saw the ? operator in Dart, it works the same way in Swift. However, Optional unwrapping in Swift is much more detailed.

Optional Unwrapping Methods

1. Force Unwrapping (!)

The simplest but also most dangerous method. If the value is nil, the app crashes:

var age: Int? = 25

// Dangerous! Would crash if age was nil
print(age!)  // Prints 25

You should only use this method when you're 100% sure. I generally try not to use it.

2. If Let - Safe Unwrapping

The method I use most. If value exists, unwrap and use it, if not, do nothing:

var email: String? = "[email protected]"

if let userEmail = email {
    print("Email: \(userEmail)")
    // Here userEmail is no longer Optional, it's directly String
} else {
    print("Email not found")
}

Very similar to Dart's null-safety. However, in Swift we need to write it more explicitly.

3. Guard Let - Early Exit

A method used in functions that I really like. If value doesn't exist, exit the function early:

func printUserInfo(name: String?, age: Int?) {
    guard let userName = name else {
        print("Name not found")
        return
    }
    
    guard let userAge = age else {
        print("Age not found")
        return
    }
    
    // Here both userName and userAge can be used safely
    print("\(userName) - \(userAge) years old")
}

printUserInfo(name: "Ahmet", age: 25)
printUserInfo(name: nil, age: 25)  // Prints "Name not found"

The nice thing about guard let is that it increases code readability. The logic of "if this value doesn't exist, exit, if it exists, continue" is very clear.

If Let vs Guard Let - Which to Use When?

At first I thought both did the same thing, but they actually have different use cases:

Use If Let:

  • When you'll do alternative operations based on an optional value
  • If value exists do one thing, if not do another thing logic
if let discount = getDiscount() {
    totalPrice = totalPrice - discount
} else {
    // No discount, continue with normal price
    applyNormalPrice()
}

Use Guard Let:

  • When a value is needed for the function to continue
  • When you need to return early if value doesn't exist
  • When you want to increase code readability
func processPayment(amount: Double?, cardNumber: String?) {
    guard let paymentAmount = amount else {
        print("Payment amount required")
        return
    }
    
    guard let card = cardNumber else {
        print("Card number required")
        return
    }
    
    // Payment process
    chargeCard(card: card, amount: paymentAmount)
}

Nil Coalescing Operator (??)

An operator we also saw in Dart. If value is nil, use a default value:

var userName: String? = nil
var displayName = userName ?? "Guest"

print(displayName)  // Prints "Guest"

I use this operator especially a lot in UI. Like showing a default image if user doesn't have a profile picture.

Optional Chaining

To check multiple Optional values in a chain:

class User {
    var profile: Profile?
}

class Profile {
    var address: Address?
}

class Address {
    var city: String?
}

let user = User()
let cityName = user.profile?.address?.city ?? "Unknown"

If any step in the chain is nil, the entire result is nil. Same logic as Dart's ?. operator.

My First Impressions

Although Swift's Optional system seems a bit challenging at first, it actually makes the code much safer. After Dart's null-safety, I was familiar with these concepts, so it was easier for me to adapt.

Guard let especially became my favorite. It incredibly increases code readability and applies the "happy path" logic very well.

Now I'm going to try making a simple app with SwiftUI. They say SwiftUI is similar to Flutter's widget system, let's see how it goes!

Conclusion

If you're also learning Swift, I recommend understanding the Optional concept well. It may seem complex at first, but you'll encounter it everywhere in iOS development. Get used to using if let or guard let instead of force unwrapping (!), your app will be more stable.

In the next post, I'll share my first experiences with SwiftUI. See you!


If you want to work with me: