Swift Tutorial · Swift Basics · Lesson 5 of 30
Swift Data Types
Int, Double, Bool, Character and String, tuples, and type aliases.
Basic types
| Type | Example | Notes |
|---|---|---|
Int |
42 |
64-bit on modern platforms |
Double, Float |
3.14 |
Double is the default |
Bool |
true |
|
Character |
"K" |
one user-visible character |
String |
"Swift" |
a value type: copies are independent |
let users = 42
let ratio = 0.75
let active = true
let grade: Character = "A"
print(type(of: users), type(of: ratio), type(of: active), type(of: grade))
print(Int.max)
print(0.1 + 0.2 == 0.3, abs((0.1 + 0.2) - 0.3) < 1e-9)
Output
Int Double Bool Character 9223372036854775807 false true
Run this on your computer — see “Get Started” for setup.
Tuples and type aliases
A tuple groups values without declaring a type, which is handy for returning several values. typealias
gives an existing type a new name.
typealias Coordinates = (latitude: Double, longitude: Double)
func minMax(_ values: [Int]) -> (min: Int, max: Int) {
(values.min()!, values.max()!)
}
let lisbon: Coordinates = (38.72, -9.14)
print(lisbon.latitude)
let range = minMax([4, 9, 1, 7])
print("min \(range.min), max \(range.max)")
let (low, high) = range
print(high - low)
Output
38.72 min 1, max 9 8
Run this on your computer — see “Get Started” for setup.
Test yourself
What's the default type for a literal like 3.14?
FloatDoubleDecimalCGFloat
Show answer
Answer: Double