Data type
Essence
A data type defines two things: the set of allowed values and the set of operations on them. Int is the integers from Int.min to Int.max plus arithmetic; Bool is two values plus &&, ||, !. The type tells the compiler how to interpret the bytes in memory and which calls are legal.
Swift's type system
- Static — the type is known at compile time, errors are caught before the program runs.
- Strong — no implicit conversions:
Int + Doubledoes not compile, you needDouble(count). - Type-inferred — annotations can be omitted, the compiler works them out.
- Basic types:
Int,Double,Float,Bool,String,Character; collectionsArray,Dictionary,Set;Optional, tuples and functions are first-class types too.
let count = 42 // Int — inferred by the compiler
let ratio = 0.5 // Double
let flag = true // Bool
let name = "Swift" // String
let ch: Character = "S"
let maybe: Int? = nil // Optional<Int>
let total = Double(count) * ratio // conversions are explicit only
Value vs reference — the key split
struct Money { var cents: Int } // value type
final class Account { var money = Money(cents: 0) } // reference type
var m1 = Money(cents: 100)
var m2 = m1
m2.cents = 5
print(m1.cents, m2.cents) // 100 5 — the copy is independent
let a1 = Account()
let a2 = a1
a2.money.cents = 7
print(a1.money.cents) // 7 — both references point to one object
struct, enum, every standard collection and String are value types: assignment copies the value (lazily for collections — copy-on-write). class, actor and closures are reference types: only the reference is copied.
Optional and abstract types
Optional<T> is an enum with cases .none and .some(T): absence is expressed in the type, not through a "magic" nil or 0. Unwrap with if let, guard let, ??, ?.; use ! only when nil is genuinely impossible.
An abstract data type is an interface without an implementation. In Swift that is a protocol: Collection describes the operations, while Array and Set implement them differently.