Bird
0
0

You want to safely unwrap two optionals and exit early if either is nil. Which is the best way to use guard for this?

hard📝 Application Q8 of 15
Swift - Control Flow
You want to safely unwrap two optionals and exit early if either is nil. Which is the best way to use guard for this?
func combine(_ a: String?, _ b: String?) {
    // Fill in guard statement
    print("Combined: \(aVal) & \(bVal)")
}
Aif let aVal = a, let bVal = b { } else { return }
Bguard let aVal = a else { return } guard let bVal = b else { return }
Cguard a != nil && b != nil else { return }
Dguard let aVal = a, let bVal = b else { return }
Step-by-Step Solution
Solution:
  1. Step 1: Understand multiple optional unwrapping with guard

    Guard allows multiple bindings separated by commas to unwrap multiple optionals safely.
  2. Step 2: Choose the best concise syntax

    guard let aVal = a, let bVal = b else { return } unwraps both optionals in one guard statement and exits early if either is nil.
  3. Final Answer:

    guard let aVal = a, let bVal = b else { return } -> Option D
  4. Quick Check:

    Use commas to unwrap multiple optionals in one guard [OK]
Quick Trick: Use commas in guard to unwrap multiple optionals at once [OK]
Common Mistakes:
  • Using multiple guard statements instead of one
  • Using if-let instead of guard for early exit
  • Checking optionals without binding values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes