Bird
0
0

Given a dictionary [String: String?] where values are optionals, how can you use if let to safely print all non-nil values?

hard📝 Application Q15 of 15
Swift - Optionals
Given a dictionary [String: String?] where values are optionals, how can you use if let to safely print all non-nil values?
Afor (key, value) in dict { print(key + ": " + value!) }
Bfor (key, value) in dict { if let val = value { print(key + ": " + val) } }
Cfor (key, value) in dict { if value != nil { print(key + ": " + value) } }
Dfor (key, value) in dict { if let value { print(key + ": " + value) } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary with optional values

    Values are optionals, so we must unwrap before printing to avoid errors.
  2. Step 2: Use if let to unwrap safely

    for (key, value) in dict { if let val = value { print(key + ": " + val) } } unwraps value into val safely and prints only non-nil values.
  3. Step 3: Check other options

    for (key, value) in dict { print(key + ": " + value!) } force unwraps which can crash; C tries to print optional directly; D syntax is invalid.
  4. Final Answer:

    for (key, value) in dict { if let val = value { print(key + ": " + val) } } -> Option B
  5. Quick Check:

    Use if let val = value to unwrap optionals [OK]
Quick Trick: Use if let to unwrap optionals before printing [OK]
Common Mistakes:
  • Force unwrapping optionals causing crashes
  • Trying to print optional directly
  • Incorrect if let syntax without variable name

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes