0
0
Swiftprogramming~10 mins

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

Choose your learning style9 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.