Complete the code to provide a default value using the nil coalescing operator.
let name: String? = nil let displayName = name [1] "Guest" print(displayName)
The nil coalescing operator ?? returns the value on its left if it is not nil; otherwise, it returns the value on its right.
Complete the code to safely unwrap the optional and provide a default integer value.
var optionalNumber: Int? = nil let number = optionalNumber [1] 10 print(number)
! which can cause runtime errors if nil.The nil coalescing operator ?? unwraps the optional if it has a value; otherwise, it uses the default value on the right.
Fix the error in the code by using the correct operator to provide a default string.
let optionalGreeting: String? = nil let greeting = optionalGreeting [1] "Hello, World!" print(greeting)
! which can cause a crash if the optional is nil.+ or && which are not for unwrapping optionals.The nil coalescing operator ?? is the correct way to provide a default value when the optional is nil.
Fill in the blank to use the nil coalescing operator to provide default values.
let scores: [String: Int?] = ["Alice": 85, "Bob": nil, "Charlie": 92] let finalScores = scores.mapValues { $0 [1] 0 } print(finalScores)
! which can cause runtime errors.|| or &&.The nil coalescing operator ?? provides a default value of 0 when the optional is nil.
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.
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)
The key is the uppercase version of the name, the value uses ?? to provide 0 if score is nil, and the filter keeps only scores greater than 0.