0
0
Swiftprogramming~10 mins

Nil represents absence of value 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 assign nil to the optional variable.

Swift
var name: String? = [1]
Drag options to blanks, or click blank then click option'
Afalse
B""
C0
Dnil
Attempts:
3 left
💡 Hint
Common Mistakes
Using empty string "" instead of nil for optional variables.
Assigning 0 or false to a String optional.
2fill in blank
medium

Complete the code to safely unwrap the optional using if let.

Swift
if let unwrappedName = name [1] {
    print("Name is \(unwrappedName)")
}
Drag options to blanks, or click blank then click option'
A== nil
B!=
C=
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using == nil which checks for nil instead of unwrapping.
Using = which is assignment, not comparison.
3fill in blank
hard

Fix the error in force unwrapping the optional variable.

Swift
let forcedName = name[1]
Drag options to blanks, or click blank then click option'
A!
B?
C.
D:
Attempts:
3 left
💡 Hint
Common Mistakes
Using ? instead of ! for force unwrapping.
Using dot or colon which are invalid here.
4fill in blank
hard

Fill both blanks to create a dictionary with optional values and check for nil.

Swift
let ages: [String: Int?] = ["Alice": [1], "Bob": [2]]
if ages["Alice"] [2] nil {
    print("Alice's age is known")
}
Drag options to blanks, or click blank then click option'
Anil
B25
C!=
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning nil to Alice when we want a known age.
Using == instead of != in the if condition.
5fill in blank
hard

Fill all three blanks to unwrap an optional with guard and provide a default value.

Swift
func greet(_ name: String?) {
    guard let unwrappedName = name [1] else {
        print("Hello, [2]!")
        return
    }
    print("Hello, [3]!")
}
Drag options to blanks, or click blank then click option'
A!=
BGuest
CunwrappedName
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of != in the guard condition.
Printing the optional variable instead of the unwrapped one.