Complete the code to assign nil to the optional variable.
var name: String? = [1]In Swift, nil means the variable has no value. Optional variables can hold nil.
Complete the code to safely unwrap the optional using if let.
if let unwrappedName = name [1] { print("Name is \(unwrappedName)") }
The if let syntax unwraps the optional only if it is not nil. The condition uses != implicitly.
Fix the error in force unwrapping the optional variable.
let forcedName = name[1]? instead of ! for force unwrapping.Force unwrapping an optional uses ! to get the value directly, but it crashes if nil.
Fill both blanks to create a dictionary with optional values and check for nil.
let ages: [String: Int?] = ["Alice": [1], "Bob": [2]] if ages["Alice"] [2] nil { print("Alice's age is known") }
The dictionary holds optional Int values. Assign 25 to Alice and check if the value is not nil.
Fill all three blanks to unwrap an optional with guard and provide a default value.
func greet(_ name: String?) {
guard let unwrappedName = name [1] else {
print("Hello, [2]!")
return
}
print("Hello, [3]!")
}The guard statement unwraps the optional if it is not nil. Otherwise, it greets a default name 'Guest'.