Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to provide a default value using the nil coalescing operator.
Swift
let name: String? = nil let displayName = name [1] "Guest"
Drag options to blanks, or click blank then click option'
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.
✗ Incorrect
The nil coalescing operator '??' returns the value on its left if it is not nil; otherwise, it returns the value on its right.
2fill in blank
mediumComplete the code to unwrap an optional integer and provide a default value using the nil coalescing operator.
Swift
var optionalNumber: Int? = nil let number = optionalNumber [1] 10
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the force unwrap operator '!' which can cause runtime errors if the optional is nil.
Using the ternary conditional operator '?' incorrectly.
✗ Incorrect
The '??' operator unwraps the optional if it has a value; otherwise, it uses the default value on the right.
3fill in blank
hardFix the error in the code by correctly using the nil coalescing operator to provide a default string.
Swift
let optionalGreeting: String? = nil let greeting = optionalGreeting [1] "Hello"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the force unwrap operator '!' which can cause a crash if the optional is nil.
Using comparison operators like '==' or ternary operators incorrectly.
✗ Incorrect
The nil coalescing operator '??' is used to provide a default value when the optional is nil.
4fill in blank
hardFill both blanks to create a dictionary comprehension that uses 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] [2] }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using force unwrap '!' which can cause runtime errors.
Using 'nil' as a default value which defeats the purpose of providing a fallback.
✗ Incorrect
The mapValues function uses '??' to unwrap the optional Int values, providing 0 as a default if nil.
5fill in blank
hardFill all three blanks to safely unwrap nested optionals using the nil coalescing operator.
Swift
struct User {
var profile: Profile?
}
struct Profile {
var nickname: String?
}
let user: User? = User(profile: Profile(nickname: nil))
let nickname = user[1]profile[2]nickname [3] "Anonymous" Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using force unwraps which can cause crashes if any optional is nil.
Confusing optional chaining syntax.
✗ Incorrect
Use optional chaining with '?.' to safely access nested optionals, then use '??' to provide a default value.