0
0
Swiftprogramming~15 mins

Optional binding with if let in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Optional binding with if let
📖 Scenario: Imagine you have a list of people's names and their optional phone numbers. Some people have phone numbers, and some don't. You want to print only the phone numbers that exist.
🎯 Goal: Build a Swift program that uses optional binding with if let to safely unwrap and print phone numbers only when they are available.
📋 What You'll Learn
Create a dictionary called contacts with these exact entries: "Alice": "123-4567", "Bob": nil, "Charlie": "987-6543"
Create a variable called contactName and set it to the string "Charlie"
Use if let optional binding with the variable phoneNumber to unwrap the phone number for contactName from contacts
Print the phone number inside the if let block using print("Phone number: \(phoneNumber)")
💡 Why This Matters
🌍 Real World
Handling optional data like phone numbers is common in apps where some information may be missing.
💼 Career
Understanding optional binding is essential for safe Swift programming, especially in iOS app development.
Progress0 / 4 steps
1
Create the contacts dictionary
Create a dictionary called contacts with these exact entries: "Alice": "123-4567", "Bob": nil, "Charlie": "987-6543"
Swift
Need a hint?

Use a dictionary with type [String: String?] to allow nil values.

2
Set the contact name
Create a variable called contactName and set it to the string "Charlie"
Swift
Need a hint?

Use let contactName = "Charlie" to store the name.

3
Use if let to unwrap the phone number
Use if let optional binding with the variable phoneNumber to unwrap the phone number for contactName from contacts
Swift
Need a hint?

Use if let phoneNumber = contacts[contactName] ?? nil to unwrap the optional phone number.

4
Print the unwrapped phone number
Print the phone number inside the if let block using print("Phone number: \(phoneNumber)")
Swift
Need a hint?

Use print("Phone number: \(phoneNumber)") inside the if let block.