0
0
Swiftprogramming~10 mins

Nil coalescing operator deep usage 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"
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 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'
A!
B?
C??
D:
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.
3fill in blank
hard

Fix 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'
A==
B!
C?:
D??
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.
4fill in blank
hard

Fill 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'
A??
B0
Cnil
D!
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.
5fill in blank
hard

Fill 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'
A?->
B??
D?.
Attempts:
3 left
💡 Hint
Common Mistakes
Using force unwraps which can cause crashes if any optional is nil.
Confusing optional chaining syntax.