Data Types and Type Inference
Prerequisites: Constants and variables
Every value in Swift has a type, which decides what you can do with it. The core types:
| Type | Example | Used for |
|---|---|---|
Int |
42, -7 |
Whole numbers |
Double |
3.14, -0.5 |
Numbers with a decimal point |
String |
"hello" |
Text |
Character |
"A" |
A single character |
Bool |
true, false |
Yes/no values |
Type inference
Swift works out the type from the value you assign. This is called type inference:
let count = 10 // Int
let price = 9.99 // Double
let title = "Swift" // String
let isReady = true // Bool
Type annotations
You can also write the type explicitly after a colon. This is a type annotation:
let score: Int = 100
let ratio: Double = 3 // stored as 3.0
let initial: Character = "A"
Annotations are needed when the value alone would give a different
type (3 would otherwise be an Int), or when you declare a
constant before assigning it.
Types are fixed
Once a variable has a type, it keeps it. Swift never quietly converts between types:
var level = 1
level = "two"
error: cannot assign value of type 'String' to type 'Int'
Checking type(of:) shows a value's type:
print(type(of: 42))
print(type(of: 4.2))
print(type(of: "42"))
Int
Double
String
Common mistakes
- Mixing types in arithmetic.
let total = 5 + 2.5works, because both are literal numbers, butlet a = 5; let b = 2.5; a + bfails —ais already anInt. Convert explicitly:Double(a) + b.