If Let
Also known as: if let optional unwrap null check nil none
● Beginner3 minBefore this: If...ElseSpec 4.2
if let runs a block only when an optional value is there, and gives you the value inside.
fn main() {
const ages = ["asha": 31, "ravi": 27]
if let age = ages["asha"] {
print("Asha is {age}")
}
if let age = ages["omar"] {
print("Omar is {age}")
} else {
print("No age for Omar")
}
}The program ran and printed:
kavach run iflet.kav
Asha is 31No age for Omar
ages["asha"] may find nothing, so its type is Int?: an Int or none. if let age = … runs the block only when there is a value, and inside it age is a plain Int.
Optional values have their own page: Optionals.