Bird
0
0

You want to write a function that takes an optional string and prints its uppercase version only if the string is non-empty. Using guard let, which code correctly implements this behavior?

hard📝 Application Q15 of 15
Swift - Optionals
You want to write a function that takes an optional string and prints its uppercase version only if the string is non-empty. Using guard let, which code correctly implements this behavior?
Afunc printUpper(_ text: String?) { guard let text = text, !text.isEmpty else { return } print(text.uppercased()) }
Bfunc printUpper(_ text: String?) { if let text = text, text.isEmpty { print(text.uppercased()) } }
Cfunc printUpper(_ text: String?) { guard let text = text else { print(text!.uppercased()) return } }
Dfunc printUpper(_ text: String?) { guard text != nil else { print(text!.uppercased()) return } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand requirements

    Function must unwrap optional and check string is not empty before printing uppercase.
  2. Step 2: Analyze options

    func printUpper(_ text: String?) { guard let text = text, !text.isEmpty else { return } print(text.uppercased()) } uses guard let to unwrap and checks !text.isEmpty in same condition, then prints uppercase. Others either misuse guard or risk force unwrapping nil.
  3. Final Answer:

    func printUpper(_ text: String?) { guard let text = text, !text.isEmpty else { return } print(text.uppercased()) } -> Option A
  4. Quick Check:

    guard let + condition filters nil and empty [OK]
Quick Trick: Combine unwrap and condition in guard let for clean checks [OK]
Common Mistakes:
  • Force unwrapping optionals without guard
  • Using if let but missing empty check
  • Placing print inside else block
  • Checking nil without unwrapping

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes