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 contactsPrint 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