Swift Tutorial · Swift Basics · Lesson 4 of 30
Swift Variables and Constants: let and var
Declare constants with let and variables with var, and let type inference choose the type.
let and var
letdeclares a constant: it's assigned once.vardeclares a variable that can change.
Prefer let; the compiler warns when a var is never changed. Types are inferred, or written after a
colon: let count: Int = 3.
let city = "Lisbon" // String, can't change
var visitors = 10 // Int, can change
visitors += 5
let price: Double = 19.99 // explicit type
print("\(city): \(visitors) visitors, ticket \(price)")
// city = "Porto" // error: cannot assign to value: 'city' is a 'let' constant
Output
Lisbon: 15 visitors, ticket 19.99
Run this on your computer — see “Get Started” for setup.
Type safety
Swift never converts between number types implicitly: convert with Double(x) or Int(y). Converting a
string with Int("42") returns an optional, because the text might not be a number.
let items = 7
let boxes = 2
print(items / boxes) // integer division
print(items % boxes)
print(Double(items) / Double(boxes)) // convert first
print(Int("42")! + 1)
print(Int("abc") as Any) // nil: not a number
Output
3 1 3.5 43 nil
Run this on your computer — see “Get Started” for setup.
Test yourself
Which keyword declares a value that can't be changed?
varletconstfinal
Show answer
Answer: let