Every value has a type
In Python you can write x = 3, then x = "three", and the language shrugs. Swift will not let you. Every constant and variable in Swift has a type, fixed when it is declared and known to the compiler before the program runs. That sounds like more work, and occasionally it is, but it buys three things that matter in large programs.
First, mistakes surface early. If you pass a price where a name was expected, the compiler stops you while you are still at your desk. Second, the compiler can generate fast code, because it knows exactly how many bytes each value takes and which machine instructions apply. Third, types are documentation that cannot go out of date: reading func send(_ message: String, to user: UserID) tells you most of what the function needs.
Swift keeps the cost low with type inference: when the type is obvious from the value, you do not have to write it. Most Swift code looks almost as light as Python while being as strictly checked as Java or C#. This lesson covers the everyday types: numbers, Booleans, strings, tuples and the three standard collections.
let and var
Definition— constant and variable
A constant, declared with let, is bound to a value once and can never be changed. A variable, declared with var, can be given new values of the same type.
let planet = "Earth" // a constant: planet can never change
var visitors = 0 // a variable: we can add to it
visitors += 1Try assigning to a constant and the compiler stops you with cannot assign to value: 'fixed' is a 'let' constant (for a constant called fixed). Professional Swift uses let by default and switches to var only when a value really must change. The compiler encourages this: if you declare a var and never change it, you get a warning suggesting let. The habit pays off when reading code: every let is a promise that this name means the same thing on every line below it.
A constant does not need its value on the same line, as long as it is assigned exactly once before use, on every path through the code:
let greeting: String
if hour < 12 {
greeting = "Good morning"
} else {
greeting = "Good afternoon"
}The compiler checks definite initialization: it proves that greeting is set exactly once before anyone reads it. Forget the else branch and the program does not compile.
Inference and annotations
When you write let count = 10, Swift infers Int; for let ratio = 0.5 it infers Double; for "hi" it infers String. You add a type annotation after a colon when you want something else, or when there is no value yet:
let ratio: Float = 0.5 // Float instead of the default Double
let initial: Character = "A" // Character instead of the default String
var scores: [Int] = [] // an empty array needs its element type spelled outAsking for a type, and naming one
When you are unsure what the compiler inferred, ask it. In an editor, Option-click (Xcode) or hover (VS Code) over a name. In a running program, type(of:) tells you:
print(type(of: 3), type(of: 3.0), type(of: "a"), type(of: (1, "a")))
// prints: Int Double String (Int, String)You can also give an existing type a second name with typealias, for example typealias Celsius = Double. A type alias is only a nickname: a Celsius value is still a Double, and the compiler will happily let you add it to a distance in metres. To get a type that the compiler keeps separate, you define a new struct, as you will in lesson 6.
Numbers that never convert behind your back
Swift's main numeric types are Int (a signed integer the size of a machine word: 64 bits on current phones and computers, 32 bits on Apple Watch), Double (a 64-bit floating-point number) and, when you need them, sized types such as Int8, UInt8, Int32, Int64 and Float. The rule that surprises newcomers is this: Swift never converts between numeric types implicitly. You cannot multiply an Int by a Double:
let n = 10
let d = 2.5
print(n * d) // error: binary operator '*' cannot be applied to operands of type 'Int' and 'Double'You must say which conversion you want: Double(n) * d gives 25.0, and n * Int(d) gives 20. That seems pedantic until you remember the bugs it prevents: in C, mixing signed and unsigned integers, or integers and floats, silently changes values in ways that have caused real security holes. In Swift, every conversion is visible.
let price = 1_250 // inferred as Int
let taxRate = 0.16 // inferred as Double
let tax = Double(price) * taxRate
print("Tax:", tax)
print(7 / 2, 7 % 2, -7 / 2, -7 % 2)
print(7.0 / 2)
print(Int(3.99), Int(-3.99))
print(Int.max)
print(UInt8.max, Int16.min)
let sum = 0.1 + 0.2
print(sum, sum == 0.3, abs(sum - 0.3) < 1e-9)Tax: 200.0
3 1 -3 -1
3.5
3 -3
9223372036854775807
255 -32768
0.30000000000000004 false trueRead it line by line:
- Underscores in a literal (
1_250) are ignored; they make long numbers readable. - Integer division truncates toward zero:
7 / 2is 3 and-7 / 2is −3, not −4 as in Python. The remainder takes the sign of the left operand, so-7 % 2is −1. If you need a remainder that is never negative, for example to wrap around a clock, you must adjust it yourself. 7.0 / 2is floating-point division because7.0is aDouble; the literal2adapts to the type it is used with.- Converting a
Doubleto anIntalso truncates toward zero. Int.maxand friends tell you the limits; going past them with+traps, as you saw in the first lesson.0.1 + 0.2is not exactly 0.3, becauseDoubleis binary floating point, just as in every other mainstream language. Compare floating-point results with a tolerance, never with==. For money, use whole numbers of the smallest unit (cents, paise, centavos) or Foundation'sDecimal.
Bool has the values true and false, and Swift does not treat numbers as Booleans: if count { ... } is an error, and you must write if count != 0. Again, one fewer way to be misunderstood.
Strings are Unicode text
A String in Swift is a sequence of Character values, and a Character is what a human reader sees as one character: an extended grapheme cluster in Unicode's terms. The letter ễ in Vietnamese can be stored as one code point or as three (an e, a circumflex and a tilde), but either way Swift counts it as one Character, and two strings that look identical compare as equal.
var name = "Nguyễn Thị Lan"
print(name.count, name.uppercased())
name += "!"
print(name)
let route = "Accra,Lomé,Cotonou,Lagos"
let stops = route.split(separator: ",")
print(stops.count, stops[1], stops.last ?? "none")
let word = "Swift"
let third = word.index(word.startIndex, offsetBy: 2)
print(word[third], word.prefix(2), String(word.reversed()))
print(word.hasPrefix("Sw"), word.contains("if"), word.lowercased())
let note = """
Line one
indented line
Line three
"""
print(note)14 NGUYỄN THỊ LAN
Nguyễn Thị Lan!
4 Lomé Lagos
i Sw tfiwS
true true swift
Line one
indented line
Line threeStrings declared with var can grow (+=, append); strings declared with let cannot. split(separator:) returns an array of pieces, and last returns an optional (there might be no pieces), hence the ?? "none".
The surprising part is indexing. You cannot write word[2]; the compiler says cannot subscript String with an Int, use a String.Index instead. Because characters have different sizes in memory (one byte for S, up to many bytes for an emoji or a Devanagari conjunct), finding "the third character" means walking from the start. Swift refuses to hide that cost behind a syntax that looks instant. Instead, you ask for an index with index(_:offsetBy:) and then subscript with it. In practice you rarely need positions at all: prefix, suffix, dropFirst, split, contains, hasPrefix and iteration with for ch in word cover most needs. For the same reason, count is not free on a String: it walks the whole string. Call it once and keep the result if you need it in a loop.
When you do need to work with the raw encoding, for a file format or a network protocol, a string offers views: word.utf8 (bytes), word.utf16 and word.unicodeScalars.
The triple-quoted multi-line string strips the indentation of the closing """ from every line, so you can indent it with the surrounding code; any extra indentation is kept, as in the second line.
Tuples and the three collections
A tuple groups a fixed number of values, possibly of different types, into one compound value: (3, "three") has type (Int, String). Elements can be named. Tuples are perfect for returning two things from a function, but for anything that lives longer or travels further, define a struct (lesson 6).
Swift's standard library has three general-purpose collections:
| Type | Literal | Ordered? | Unique? | Look up by |
|---|---|---|---|---|
Array, written [Element] | [1, 2, 3] | yes | no | position, from 0 |
Dictionary, written [Key: Value] | ["a": 1] | no | keys are | key |
Set | [1, 2, 3] with a Set annotation | no | yes | membership |
let point = (x: 3, y: -2)
let (px, py) = point
print(point.x + point.y, px * py)
var cities = ["Lima", "Hanoi"]
cities.append("Cairo")
cities.insert("Oslo", at: 0)
print(cities, cities.count, cities[2])
var stock = ["apples": 12, "mangoes": 5]
stock["pears"] = 7
stock["apples", default: 0] += 3
print(stock["mangoes"] ?? 0, stock["kiwis"] ?? 0, stock["apples"] ?? 0)
print(stock.keys.sorted())
let morning: Set = ["Ana", "Kofi", "Mei", "Ravi"]
let evening: Set = ["Mei", "Omar", "Ravi"]
print(morning.intersection(evening).sorted())
print(morning.union(evening).count, morning.contains("Omar"))
var original = [1, 2]
var copy = original
copy.append(3)
print(original, copy)1 -6
["Oslo", "Lima", "Hanoi", "Cairo"] 4 Hanoi
5 0 15
["apples", "mangoes", "pears"]
["Mei", "Ravi"]
5 false
[1, 2] [1, 2, 3]Some details worth slowing down for:
- Arrays check their bounds.
cities[10]would trap, not read random memory. Usecities.first,cities.lastorcities.indices.contains(i)when an index might be out of range. - Looking up a dictionary key gives an optional, because the key might be missing:
stock["kiwis"]isnil, and?? 0supplies a default. Thestock["apples", default: 0] += 3form reads the value or a default, changes it and stores it back, all in one step. This is the idiomatic way to count things. - Dictionaries and sets have no stable order. Swift seeds its hash function randomly each time a program starts, to defend servers against attacks that feed in deliberately colliding keys. Print a dictionary or a set directly and the order can change from one run to the next. Whenever order matters (output, tests), sort first, as the program does with
keys.sorted(). - Collections are values. The last two lines copy an array and change the copy; the original is untouched. In Python both names would refer to the same list and both would show
[1, 2, 3]. Swift's arrays, dictionaries, sets and strings are value types: assignment gives you an independent copy. They are not slow because of it: the copy shares storage until one side is modified (copy-on-write). Lesson 6 explains how, and why it is one of the best ideas in the language.
A let collection cannot be changed at all, not even by appending. A var collection can.
Common misconceptions
Misconception
"let makes code slower, or is only for numbers." let is about meaning, not speed, and it works for every type, including arrays and strings. A let array is completely immutable. Use let everywhere you can; the compiler tells you when you need var.
Misconception
"Swift's integer division works like Python's." Python's // rounds toward minus infinity, so -7 // 2 is −4. Swift's / on integers truncates toward zero, so -7 / 2 is −3, and -7 % 2 is −1. Code ported from Python that handles negative numbers is a classic source of off-by-one bugs.
Misconception
"count is the number of bytes in a string." count is the number of characters as a reader sees them. For bytes, use utf8.count. They are equal only for plain ASCII text, which is exactly the kind of text that tests are written with and real users do not type.
Misconception
"A dictionary prints in the order I inserted the keys." It does not, and the order can differ from one run of the same program to the next. If you need insertion order, keep an array of keys alongside, or use an ordered collection from the open-source Swift Collections package.
What experienced Swift programmers do
They rarely write types that the compiler can infer, but they always annotate public API (function parameters and return types must be annotated anyway) and empty collections. They use Int for counts and indices even when values can never be negative, because mixing Int and UInt would force conversions everywhere; sized and unsigned types are for binary formats and hardware. They model money and identifiers with their own small types rather than bare Double and String, a habit you will learn in lesson 6. And they treat strings as text, not as arrays of bytes: when they really need bytes, they say so with utf8.
Exercises
1. Constants, variables and types
Warm-upComputationalWhat does this line print?
print(-9 / 4, -9 % 4)
2. Constants, variables and types
CoreComputationalWhat does this program print?
var a = ["x"]
var b = a
b.append("y")
a.append("z")
print(a.count + b.count)
3. Constants, variables and types
CoreComputationalEach flag emoji is made of two Unicode scalars (two regional indicator letters: K and E for Kenya, J and P for Japan). What does print("🇰🇪🇯🇵".count) print?
4. Constants, variables and types
CoreComputationalWhat does this program print?
var tally: [Character: Int] = [:]
for ch in "banana" {
tally[ch, default: 0] += 1
}
print(tally["a"] ?? 0, tally["n"] ?? 0, tally["z"] ?? 0)
5. Constants, variables and types
StretchComputationalEach line below is a whole program. Which ones compile? List the letters (for example A, B).
- A.
let a: [Int] = [] - B.
var b = [] - C.
let c = [1, 2.5] - D.
let n = 3then, on the next line,let t = n + 0.5 - E.
let e = ["a": 1, "b": "two"] - F.
let total = 3 + 0.5
6. Constants, variables and types
CoreHumanWhy does Swift refuse word[2] when word is a String?
Further reading and resources
- The Swift Programming Language: The BasicsThe official book's chapters on the basics, strings and characters, and collection types.
- Swift standard libraryReference documentation for Int, Double, String, Array, Dictionary, Set and the rest.
- Unicode Standard Annex 29, Text SegmentationThe rules that decide what counts as one user-perceived character, which Swift's String follows.