Bird
0
0

You have an optional string var input: String? = nil. You want to print its value only if it exists, otherwise print "No input". Which code safely achieves this without crashing?

hard📝 Application Q15 of 15
Swift - Optionals
You have an optional string var input: String? = nil. You want to print its value only if it exists, otherwise print "No input". Which code safely achieves this without crashing?
Aprint(input!)
Bprint(input ?? "No input")
Cprint(input!) ?? "No input"
Dprint(input != nil ? input! : nil)
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    Print the value if it exists; otherwise print "No input" safely without crash.
  2. Step 2: Analyze options

    print(input ?? "No input") uses nil-coalescing operator ?? to provide default string if input is nil, avoiding force unwrap crash.
  3. Final Answer:

    print(input ?? "No input") -> Option B
  4. Quick Check:

    Use ?? to safely unwrap or default [OK]
Quick Trick: Use ?? to provide default instead of force unwrap [OK]
Common Mistakes:
  • Force unwrapping nil causing crash
  • Misusing ?? with force unwrap
  • Printing nil instead of default string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes