Bird
0
0

Which of the following Swift code snippets correctly unwraps an optional String? using if let?

easy📝 Syntax Q3 of 15
Swift - Optionals
Which of the following Swift code snippets correctly unwraps an optional String? using if let?
Aif optionalString != nil { print(optionalString!) }
Bif let unwrapped = optionalString { print(unwrapped) }
Cif let optionalString { print(optionalString) }
Dif optionalString = nil { print(optionalString) }
Step-by-Step Solution
Solution:
  1. Step 1: Understand optional binding syntax

    Optional binding with if let requires declaring a new constant to unwrap the optional safely.
  2. Step 2: Analyze each option

    • A: Correct syntax: declares unwrapped to hold the unwrapped value.
    • B: Uses force unwrap ! inside the block, which is unsafe.
    • C: Missing assignment in if let, invalid syntax.
    • D: Uses assignment = instead of binding, invalid syntax.
  3. Final Answer:

    if let unwrapped = optionalString { print(unwrapped) } -> Option B
  4. Quick Check:

    Proper if let syntax requires a new constant assignment [OK]
Quick Trick: Use 'if let constant = optional' to unwrap safely [OK]
Common Mistakes:
  • Forgetting to assign the optional to a new constant
  • Using force unwrap inside the if block
  • Using '=' instead of 'let' in optional binding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes