Component - Variables (let, var) and type inference
This Swift UI component shows how to declare variables using let and var. It also demonstrates type inference, where Swift figures out the variable type automatically.
This Swift UI component shows how to declare variables using let and var. It also demonstrates type inference, where Swift figures out the variable type automatically.
VStack ├── Text (title) ├── Text (let variable display) ├── Text (var variable display) └── Button (change var variable)
let do in Swift?let usagelet is used to declare constants in Swift, which means their value cannot be changed after assignment.varvar, which declares variables that can change, let makes the value fixed.let = constant [OK]score with initial value 10 in Swift?var is used to declare variables that can change, and the syntax is var name = value.var score = 10 uses correct syntax. let score = 10 declares a constant, not a variable. score var = 10 and variable score = 10 are invalid syntax.var name = "Alice" name = "Bob" print(name)
name is declared with var, so it can be changed after initial assignment.name is "Alice". Then it is reassigned to "Bob". The print statement outputs the current value, "Bob".let age = 25 age = 30
age is declared with let, making it a constant.var x = 5 let y = x x = 10 print(y)
x is 5 initially. y is a constant assigned the current value of x, which is 5.x to 10 does not affect y, because y holds its own copy of the value 5.Pass the test and this pattern moves unknown