Introduction
Nil means there is no value. It shows something is empty or missing.
Nil means there is no value. It shows something is empty or missing.
var name: String? = nil
Use ? after the type to make it optional, meaning it can hold a value or nil.
Assign nil to show no value is present.
var age: Int? = nil
var message: String? = "Hello"
message = nilThis program shows how to use nil to check if a value exists. First, petName is nil, so it prints no name. Then we give petName a value and print it safely.
var petName: String? = nil if petName == nil { print("No pet name given.") } else { print("Pet name is \(petName!).") } petName = "Buddy" if let name = petName { print("Pet name is \(name).") }
Always use optional binding (if let) to safely use values that might be nil.
Force unwrapping with ! can cause errors if the value is nil.
Nil means no value or absence of value.
Use optionals (with ?) to allow nil values.
Check for nil before using optional values to avoid errors.
nil represent in Swift?nil means there is no value assigned to a variable or constant.? after a type makes it optional, allowing it to hold a value or nil.var name: String? = nil
if name == nil {
print("No name provided")
} else {
print(name!)
}name is declared as optional String and assigned nil.name == nil is true, so the code prints "No name provided".var age: Int? age = nil print(age!)
! on an optional tries to get its value directly.age is nil, force unwrapping causes a runtime crash.0 if nil?
let ages: [String: Int?] = ["Alice": 30, "Bob": nil, "Carol": 25]
// Fill in the blank
for (name, age) in ages {
print("\(name): \(____)")
}Int?, meaning each age can be an integer or nil.age ?? 0 safely unwraps age or uses 0 if nil.Pass the test and this pattern moves unknown