Bird
0
0

Given a dictionary of optional ages, write Swift code using if let to print the age only if it exists for the key "John".

hard📝 Application Q8 of 15
Swift - Optionals
Given a dictionary of optional ages, write Swift code using if let to print the age only if it exists for the key "John".
Which code snippet correctly does this?
Aif let age = ages["John"] { print("John's age is \(age)") }
Bif let age = ages[John] { print("John's age is \(age)") }
Cif let age = ages["John"]! { print("John's age is \(age)") }
Dif let age = ages["John"] ?? 0 { print("John's age is \(age)") }
Step-by-Step Solution
Solution:
  1. Step 1: Access dictionary optional value

    Accessing ages["John"] returns an optional Int.
  2. Step 2: Use if let to unwrap safely

    Using if let age = ages["John"] unwraps the optional if it exists.
  3. Final Answer:

    if let age = ages["John"] { print("John's age is \(age)") } -> Option A
  4. Quick Check:

    Optional dictionary value unwrapped with if let [OK]
Quick Trick: Use if let with dictionary[key] to unwrap optional values [OK]
Common Mistakes:
  • Using unquoted key in dictionary access
  • Force unwrapping with ! causing crash
  • Using nil coalescing inside if let

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes