Concept Flow - Nil represents absence of value
Declare Optional Variable
Variable has value?
No→Variable is nil
Yes
Use the value safely
End
This flow shows how an optional variable can either hold a value or be nil, representing absence of value.
var name: String? = nil if name == nil { print("No name provided") } else { print("Name is \(name!)") }
| Step | Variable 'name' | Condition 'name == nil' | Branch Taken | Output |
|---|---|---|---|---|
| 1 | nil | true | if branch | No name provided |
| 2 | "Alice" | false | else branch | Name is Alice |
| Variable | Start | After Step 1 | Final |
|---|---|---|---|
| name | nil | nil | nil |
Optional variables can hold a value or nil. Nil means no value is present. Always check for nil before using optional values. Use '!' to force unwrap only if sure it's not nil. Safe coding avoids runtime 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