Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Swift - Optionals
What will be the output of this code?
class Cat {
  var age: Int
  init(age: Int) { self.age = age }}

var cat: Cat? = nil
print(cat?.age ?? -1)
A-1
Bnil
C0
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand optional chaining with nil optional

    Since cat is nil, cat?.age returns nil.
  2. Step 2: Use nil-coalescing operator

    The expression cat?.age ?? -1 returns -1 because left side is nil.
  3. Final Answer:

    -1 -> Option A
  4. Quick Check:

    Nil optional with ?? returns default [OK]
Quick Trick: Use ?? to provide default when optional chaining returns nil [OK]
Common Mistakes:
  • Expecting nil printed instead of default
  • Forgetting ?? operator
  • Assuming runtime error on nil optional

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes