Swift Variables and Data Types
Variables and constants store values so your program can use them later.
let and var
| Keyword | Creates | Can change? |
|---|---|---|
let | a constant | No |
var | a variable | Yes |
Example
let name = "Ali"
var score = 70
score = 85
print("\(name) scored \(score)")Ali scored 85
Writing name = "Bilal" would give an error, because name is a constant.
Use let whenever the value does not need to change. Xcode even warns you when a var is never changed.
Type Inference and Annotations
Swift works out the type from the value. This is called type inference. You can also write the type yourself with a colon. This is a type annotation.
Example
let city = "Karachi" // inferred as String
let population: Int = 20000000
let rate: Double = 278.5
var isOpen: Bool = true
isOpen = false
print(city, population, rate, isOpen)Karachi 20000000 278.5 false
Once a variable has a type, it cannot hold a different type. A String variable can never store a number.
Data Types
| Type | Stores | Example |
|---|---|---|
Int | Whole numbers | 25 |
Double | Decimal numbers (high precision) | 3.75 |
Float | Decimal numbers (less precision) | 3.75 |
Bool | true or false | true |
String | Text | "Hyderabad" |
Character | One character | "A" |
A Character also uses double quotes, but you must write the type: let grade: Character = "A".
Type Conversion
Swift never mixes types by itself. Int plus Double is an error. Convert one of them first:
Example
let pens = 3
let pricePerPen = 25.5
let total = Double(pens) * pricePerPen
print(total)
let rounded = Int(total)
print(rounded)
let label = "Pens: " + String(pens)
print(label)76.5 76 Pens: 3
Int(76.5) cuts off the decimal part. It does not round.
Converting Text to Numbers
Turning a string into a number may fail, for example Int("hello"). So Swift gives back an optional, which is either a number or nil (no value). You will learn optionals properly in the conditions lesson. For now, ?? gives a default value:
Example
let input = "42"
let number = Int(input) ?? 0
print(number + 8)
let bad = Int("abc") ?? 0
print(bad)50 0
Naming Rules
- Names can contain letters, numbers and underscores, but cannot start with a number
- Use camelCase:
studentName,totalPrice - Names cannot be Swift keywords such as
letorclass
Exercise
Exercise
Why does let x = 5 + 2.5 work, but let a = 5; let b = 2.5; let c = a + b fails?
