Bird
0
0

Given the following Swift code, what will be the value of finalValue?

hard📝 Application Q15 of 15
Swift - Operators and Expressions
Given the following Swift code, what will be the value of finalValue?
func getValue() -> Int? { return nil }
let a: Int? = nil
let b: Int? = getValue()
let c: Int? = 7
let finalValue = a ?? b ?? c ?? 0
Anil
B0
C7
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate each optional in the chain

    a is nil, b is nil (from getValue()), c is 7 (non-nil).
  2. Step 2: Apply nil coalescing operator

    The expression a ?? b ?? c ?? 0 returns the first non-nil value, which is 7.
  3. Final Answer:

    7 -> Option C
  4. Quick Check:

    First non-nil in chain = 7 [OK]
Quick Trick: Chain ?? to find first non-nil, else default [OK]
Common Mistakes:
  • Assuming function return nil means error
  • Ignoring that c is non-nil
  • Thinking default 0 is returned always

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes