Bird
Raised Fist0
Swiftprogramming~10 mins

Nil coalescing operator (??) in Swift - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to provide a default value using the nil coalescing operator.

Swift
let name: String? = nil
let displayName = name [1] "Guest"
print(displayName)
Drag options to blanks, or click blank then click option'
A??
B||
C&&
D!
Attempts:
3 left
💡 Hint
Common Mistakes
Using logical operators like || or && instead of the nil coalescing operator.
Using the force unwrap operator ! which can cause a crash if the value is nil.
2fill in blank
medium

Complete the code to safely unwrap the optional and provide a default integer value.

Swift
var optionalNumber: Int? = nil
let number = optionalNumber [1] 10
print(number)
Drag options to blanks, or click blank then click option'
A!
B??
C&&
D||
Attempts:
3 left
💡 Hint
Common Mistakes
Using force unwrap ! which can cause runtime errors if nil.
Using logical operators which do not work with optionals.
3fill in blank
hard

Fix the error in the code by using the correct operator to provide a default string.

Swift
let optionalGreeting: String? = nil
let greeting = optionalGreeting [1] "Hello, World!"
print(greeting)
Drag options to blanks, or click blank then click option'
A!
B+
C??
D&&
Attempts:
3 left
💡 Hint
Common Mistakes
Using ! which can cause a crash if the optional is nil.
Using operators like + or && which are not for unwrapping optionals.
4fill in blank
hard

Fill in the blank to use the nil coalescing operator to provide default values.

Swift
let scores: [String: Int?] = ["Alice": 85, "Bob": nil, "Charlie": 92]
let finalScores = scores.mapValues { $0 [1] 0 }
print(finalScores)
Drag options to blanks, or click blank then click option'
A??
B!
Attempts:
3 left
💡 Hint
Common Mistakes
Using force unwrap ! which can cause runtime errors.
Using logical operators like || or &&.
5fill in blank
hard

Fill all three blanks to create a dictionary that maps names to their uppercase keys and uses the nil coalescing operator to provide default scores greater than zero.

Swift
let rawScores: [String: Int?] = ["dave": nil, "emma": 75, "frank": nil]
let processedScores = [[1]: [2] for (name, score) in rawScores if ([2] [3] 0)]
print(processedScores)
Drag options to blanks, or click blank then click option'
Aname.uppercased()
Bscore ?? 0
C>
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using raw name instead of uppercase for keys.
Not using nil coalescing operator to handle nil scores.
Using wrong comparison operator in the filter.

Practice

(1/5)
1. What does the nil coalescing operator ?? do in Swift?
easy
A. It unwraps an optional without checking for nil.
B. It provides a default value if an optional is nil.
C. It converts a non-optional to an optional.
D. It forces a runtime error if the optional is nil.

Solution

  1. Step 1: Understand optional values

    Optionals may contain a value or nil (no value).
  2. Step 2: Role of nil coalescing operator

    The operator ?? returns the optional's value if it exists; otherwise, it returns the default value provided.
  3. Final Answer:

    It provides a default value if an optional is nil. -> Option B
  4. Quick Check:

    Nil coalescing = default value if nil [OK]
Hint: Remember: ?? means "use this if nil" [OK]
Common Mistakes:
  • Thinking ?? unwraps without nil check
  • Confusing ?? with forced unwrapping (!)
  • Assuming ?? converts types
2. Which of the following is the correct syntax to use the nil coalescing operator in Swift?
easy
A. let value = optionalValue !! defaultValue
B. let value = optionalValue ?: defaultValue
C. let value = optionalValue ? defaultValue
D. let value = optionalValue ?? defaultValue

Solution

  1. Step 1: Recall the syntax of nil coalescing

    The nil coalescing operator is written as ?? between an optional and a default value.
  2. Step 2: Match correct syntax

    let value = optionalValue ?? defaultValue uses ?? correctly: let value = optionalValue ?? defaultValue.
  3. Final Answer:

    let value = optionalValue ?? defaultValue -> Option D
  4. Quick Check:

    Correct syntax uses ?? [OK]
Hint: Look for double question marks ?? in syntax [OK]
Common Mistakes:
  • Using ?: which is from other languages
  • Using single ? without ??
  • Using !! which is invalid
3. What will be the output of the following Swift code?
var name: String? = nil
let displayName = name ?? "Guest"
print(displayName)
medium
A. Guest
B. Optional("Guest")
C. nil
D. Error: Cannot print optional

Solution

  1. Step 1: Check the optional value

    The variable name is nil.
  2. Step 2: Apply nil coalescing operator

    The expression name ?? "Guest" returns "Guest" because name is nil.
  3. Final Answer:

    Guest -> Option A
  4. Quick Check:

    nil ?? "Guest" = "Guest" [OK]
Hint: If optional is nil, ?? returns the default value [OK]
Common Mistakes:
  • Expecting nil to print
  • Thinking print shows Optional(...)
  • Confusing ?? with forced unwrap
4. Identify the error in this Swift code snippet using the nil coalescing operator:
let age: Int? = 25
let userAge = age ??
print(userAge)
medium
A. Optional variable cannot be used with ??
B. print statement syntax is incorrect
C. Missing default value after ?? operator
D. age should not be optional

Solution

  1. Step 1: Check nil coalescing usage

    The operator ?? must be followed by a default value to use if the optional is nil.
  2. Step 2: Identify missing default value

    In the code, age ?? is incomplete because no default value is provided after ??.
  3. Final Answer:

    Missing default value after ?? operator -> Option C
  4. Quick Check:

    ?? needs a value after it [OK]
Hint: Always provide a value after ?? [OK]
Common Mistakes:
  • Leaving ?? without default value
  • Thinking optional can't be used with ??
  • Misplacing print statement
5. Given the dictionary let scores: [String: Int?] = ["Alice": 85, "Bob": nil], which expression correctly uses the nil coalescing operator to get Bob's score or 0 if nil?
hard
A. let bobScore = scores["Bob"] ?? nil ?? 0
B. let bobScore = scores["Bob"]! ?? 0
C. let bobScore = scores["Bob"] ?? Optional(0)
D. let bobScore = scores["Bob"] ?? 0

Solution

  1. Step 1: Understand dictionary value type

    The dictionary stores optional Int values: Int? inside the dictionary optional lookup, so scores["Bob"] returns Int??.
  2. Step 2: Use nil coalescing correctly

    Chaining scores["Bob"] ?? nil ?? 0 first flattens the double optional to Int? (returns inner value or nil), then applies ?? 0 to provide 0 if nil, yielding Int. For "Bob", some(nil) ?? nil = nil, then nil ?? 0 = 0.
  3. Final Answer:

    let bobScore = scores["Bob"] ?? nil ?? 0 -> Option A
  4. Quick Check:

    ?? nil ?? 0 handles [Key: Opt<V>] [OK]
Hint: Chain ?? nil ?? 0 for dict of optionals [OK]
Common Mistakes:
  • Forcing unwrap before ?? causing crash
  • Direct ?? 0 causes type mismatch
  • Optional(0) doesn't handle inner nil
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard