Bird
0
0

Given this Swift code, how can you safely print the length of the optional string text?

hard📝 Application Q15 of 15
Swift - Optionals
Given this Swift code, how can you safely print the length of the optional string text?
var text: String? = "Hello"
// Your code here
Aprint(text ?? 0)
Bif let safeText = text { print(safeText.count) } else { print(0) }
Cprint(text!)
Dprint(text.count)
Step-by-Step Solution
Solution:
  1. Step 1: Understand optional unwrapping with if let

    Using if let safely unwraps the optional text only if it has a value, avoiding crashes.
  2. Step 2: Use unwrapped value to get length

    Inside the if let block, safeText.count gives the length. If text is nil, print 0.
  3. Step 3: Check other options

    print(text.count) tries to access count on optional directly (error). print(text!) force unwraps without check (unsafe). print(text ?? 0) uses nil coalescing but mismatches types.
  4. Final Answer:

    if let safeText = text { print(safeText.count) } else { print(0) } -> Option B
  5. Quick Check:

    Use if let to safely unwrap optionals [OK]
Quick Trick: Use if let to unwrap optionals safely [OK]
Common Mistakes:
  • Forcing unwrap without checking nil
  • Accessing properties on optional without unwrapping
  • Using nil coalescing with wrong types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes