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
}
}
Function must unwrap optional and check string is not empty before printing uppercase.
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.
Final Answer:
func printUpper(_ text: String?) {
guard let text = text, !text.isEmpty else {
return
}
print(text.uppercased())
} -> Option A
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
Master "Optionals" in Swift
9 interactive learning modes - each teaches the same concept differently