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.