Introduction to Swift

Introduction to Swift in Swift: Picture the table saw at the heart of a serious woodworking shop.

The Analogy: The Guarded Table Saw

Picture the table saw at the heart of a serious woodworking shop. It is the single most useful machine on the floor and also the single most dangerous: a steel blade spinning fast enough to cross-cut a hardwood plank in a heartbeat, and fast enough to do the same to a hand. A modern professional saw arrives wrapped in safety hardware that is engaged the moment you switch it on. A clear guard sits over the teeth, a riving knife rides just behind the blade so the wood cannot pinch and kick back into your body, and a flesh-sensing brake drives a soft cartridge into the blade within a few thousandths of a second if skin ever brushes it. On this machine the safe way to cut is also the default way to cut; you do not earn safety by remembering to add it.

Swift is that saw, and its guards are engaged before you type a single character. Naming a value with let makes it an immutable constant, so it can never be reassigned by a careless line three screens away. The type system refuses to add an Int to a Double behind your back, the same way the riving knife refuses to let the board close on the blade. Integer arithmetic traps loudly on overflow instead of silently wrapping around to a nonsense value, and reading past the end of an array halts the program rather than handing you whatever bytes happened to sit next in memory. None of this was switched on by you; it is simply the resting posture of the machine, and it is why beginners write surprisingly robust Swift almost by accident.

The saw still lets you make genuinely dangerous cuts, but only when you deliberately remove a guard, and only in a way that everyone can see. To force a value you are certain is present you write a visible exclamation mark; to let arithmetic wrap on purpose you reach for the &+ operator; to convert a number and accept the loss you spell out Double(x) or Int(x). Each of these is a distinct, searchable gesture, the equivalent of physically lifting the blade guard and setting it aside on the bench. A reviewer reading the code later can find every single spot where a guard came off, because the language made removing it an explicit act rather than a silent default.

The failure mode is the apprentice who tapes the guard up and disconnects the brake because pausing to think feels slow. For the first hour he really is faster than everyone else on the floor. Then a hidden knot grabs the blade mid-cut, the plank kicks straight back, and the injury the machine was engineered to prevent is exactly the one that lands. Peppering a codebase with force-unwraps, declaring everything var out of habit, and papering over type errors with force casts is the identical bargain: you disable the very features that were holding the crash at bay, and the crash returns at the least convenient possible moment, usually in front of a user.


Syntax or Core Structure

Swift makes the safe choice the default choice. Constants come first with let; you reach for var only when a value genuinely has to change over its lifetime. The compiler infers a static type from each literal, so annotations are rare, yet the type is fixed and fully checked before the program ever runs.

// Constants are immutable; variables are mutable. Prefer let.
let language = "Swift"
let year = 2014
var version = 5

version = 6   // reassigning a var is allowed

// Type inference: the compiler reads each literal and fixes a type.
let pi = 3.14159        // inferred as Double
let isModern = true     // inferred as Bool
let grade = "A"         // inferred as String

// String interpolation splices values straight into text.
print("\(language) shipped in \(year), now at version \(version).")
print("pi is a \(type(of: pi)); grade is a \(type(of: grade)).")

Output:

Swift shipped in 2014, now at version 6.
pi is a Double; grade is a String.

Each line reads like a plain statement, yet every name is fully typed and checked at compile time. Reassigning version works because it is a var; attempting the same assignment on language would be rejected by the compiler before the program could run, which is the guard doing its job.


Technical Depth: Inference, Value Semantics, and Explicit Danger

Three ideas explain most of Swift's early ergonomics: how types are inferred so you rarely annotate, why constants are both cheap and genuinely safe, and how the language forces every unsafe act to be spelled out where a reader can find it.

Type inference and its default types

When you write a literal with no annotation, Swift assigns a canonical type. Whole numbers become Int, numbers with a decimal point become Double, quoted text becomes String, and true/false become Bool. You override the default only when you need a narrower or more specific type.

Literal you writeType Swift infersWhen to annotate instead
let n = 42Intyou need Int8, UInt, or similar
let d = 3.14Doubleyou need a 32-bit Float
let flag = trueBoolnever; a Bool is unambiguous
let s = "hi"Stringyou need a single Character
let c: Character = "!"Characteralways; a quote defaults to String

Value semantics keep constants honest

Most Swift types (numbers, strings, arrays, dictionaries, and structs) are value types: assigning one to another copies it rather than sharing a reference. A constant array therefore cannot grow, and passing it to a function cannot mutate the caller's copy. This is why let is stronger than a promise not to reassign: the underlying value cannot be edited in place through some other name either.

let base = [1, 2, 3]
var working = base      // this copies the array, it does not share it
working.append(4)
print("base    = \(base)")
print("working = \(working)")

Output:

base    = [1, 2, 3]
working = [1, 2, 3, 4]

Appending to working leaves base untouched because the assignment made an independent copy. In a reference-based language the two names might point at one shared array, and the append would silently lengthen base as well.

Danger is always opt-in

The unsafe operations still exist, but each has its own distinct, visible spelling, so a reviewer can locate every one of them with a simple search.

Safe defaultExplicit opt-outWhat the opt-out means
let x = a + b traps on overflowa &+ bwrap around silently, on purpose
optional ?? fallbackoptional!crash right now if the value is missing
Int(exactly: d) returns optionalInt(d)truncate the fraction toward zero
try someCall()try! someCall()crash instead of handling the error

Because the dangerous form always looks different from the safe form, code review and text search both work: you can grep a whole project for &+ or try! and see every place a guard was deliberately removed.

Explicit conversion puts you in control

Mixing numeric types is a compile error, not a silent coercion, so you convert on purpose and decide what happens to the fractional part in the process.

let total = 47
let people = 4
let whole = total / people                 // Int / Int truncates
let exact = Double(total) / Double(people)  // convert first, then divide
print("Whole slices each: \(whole)")
print("Exact share:       \(exact)")

Output:

Whole slices each: 11
Exact share:       11.75

Integer division discards the remainder, so 47 / 4 is 11; converting both operands to Double first preserves the 0.75. The compiler made you choose between those outcomes rather than quietly guessing one for you.

Interpolation composes text predictably

String interpolation evaluates each slot in order and converts the value using its standard textual form, so a line of output is fully determined by its inputs, with no hidden locale or formatting surprises. That property makes interpolated strings easy to test, because the same values always produce exactly the same characters.

let city = "Oslo"
let highC = 19
let lowC = 11
print("\(city): high \(highC)C, low \(lowC)C")
print("Spread is \(highC - lowC)C between the two.")

Output:

Oslo: high 19C, low 11C
Spread is 8C between the two.

Each slot can hold a full expression, not just a bare variable, which is why highC - lowC computes directly inside the quotes. The compiler still type-checks everything inside a slot, so an interpolation that references a misspelled name fails to build rather than silently printing an empty gap where the value should be.


Real World Example: Aggregating Sensor Readings

Consider a short routine that summarizes one run of temperature samples taken from a single device. It leans entirely on Swift's defaults: constants throughout, safe optional access for the edge cases, and explicit conversion for the average.

// A batch of temperature samples (Celsius) from one sensor run.
let readings = [21.5, 22.0, 20.75, 23.25, 22.5]

// .first returns an optional, so it is safe even on an empty array.
let firstSample = readings.first ?? 0.0

// reduce sums the array; count is an Int, so convert it for the average.
let sum = readings.reduce(0.0, +)
let average = sum / Double(readings.count)

// min() and max() are optionals too, covering the empty case.
let low = readings.min() ?? 0.0
let high = readings.max() ?? 0.0

print("Samples: \(readings.count)")
print("First:   \(firstSample)")
print("Average: \(average)")
print("Range:   \(low) to \(high)")

Output:

Samples: 5
First:   21.5
Average: 22.0
Range:   20.75 to 23.25

Every value here is a let, so nothing in the summary can be mutated after it is computed, which makes the routine easy to reason about at a glance. The array literal fixes both the element type (Double) and the order, so reduce walks the samples deterministically and the sum is exactly 110.0, giving an average of 22.0 over the five readings.

The optional-aware calls (first, min, max) mean the code never indexes blindly into the array, so a shorter or empty batch cannot trigger an out-of-range crash. On this input the ?? 0.0 fallbacks never actually fire, and the report reads cleanly across a range of 20.75 to 23.25.

That very convenience hides a real design flaw. If readings were empty, sum would be 0.0 and readings.count would be 0, so average becomes 0.0 / 0.0, which evaluates to nan; meanwhile the ?? 0.0 fallbacks quietly report a low and high of 0.0. The summary would then look like a valid measurement of a freezing sensor instead of an obvious "no data" condition. A guard !readings.isEmpty else { ... } at the top, returning an optional summary, would surface the empty run honestly rather than disguising it as real data.


Common Mistakes

  1. Defaulting to var. Reaching for var out of habit throws away immutability for no benefit. Start with let and let the compiler tell you when a value genuinely needs to change.
  2. Force-unwrapping to silence the compiler. Writing value! just to make an error disappear moves the crash to runtime. Unwrap with if let, guard let, or ?? so a missing value is handled, not detonated.
  3. Expecting implicit numeric conversion. someInt + someDouble does not compile. Convert explicitly with Double(someInt) and decide deliberately what happens to the fractional part.
  4. Assuming integer division keeps the remainder. 7 / 2 is 3, not 3.5. Convert an operand to Double before dividing whenever you need the fractional result.
  5. Ignoring overflow semantics. Ordinary arithmetic traps on overflow; if you actually want wrap-around you must say &+, &-, or &* on purpose, not assume it happens for you.
  6. Indexing an array without checking bounds. items[i] crashes if i is out of range. Use .first, .last, or indices.contains(i) when the index is not guaranteed valid.
  7. Confusing reassignment with mutation of a constant. A let array cannot be appended to at all; if you need to add elements, the binding itself must be declared var.
  8. Over-annotating obvious types. Writing let count: Int = 0 everywhere adds noise the compiler already infers. Annotate only for a non-default type or genuine documentation value.
  9. Treating String and Character as interchangeable. A double-quoted literal is a String even when it holds one symbol; a single Character requires an explicit type annotation.

Best Practices

  • Reach for let first. Make mutability the exception you justify, not the default you tolerate. Compilers optimize constants aggressively and readers trust that they never change.
  • Let inference handle the routine typing. Skip annotations for obvious literals and add them only where a non-default type or clearer intent earns its keep.
  • Unwrap optionals deliberately. Prefer guard let for early exits and if let for local use; reserve ! for values a surrounding invariant already guarantees are present.
  • Convert numbers at the boundary. Turn incoming Int and Double values into the type you need once, near where they enter, rather than scattering conversions through the logic.
  • Make dangerous operations visible. If you genuinely need &+, try!, or a force cast, isolate it and comment why, so a reviewer can see the guard came off on purpose.
  • Prefer value types for plain data. Structs and arrays copy on assignment, which eliminates a whole class of aliasing bugs where a distant change mutates your data unexpectedly.
  • Name constants for meaning, not type. maxRetries communicates intent; intValue3 does not. Good names are what keep inference-heavy code readable.
  • Guard against empty collections. Before averaging or reducing, confirm the collection is non-empty so that fallback values never disguise missing data as a real measurement.

Practice Exercises

  1. Constant audit. Take a short snippet that declares five values with var and change every binding that never gets reassigned to let. Note which ones the compiler would have let you leave as var and which it now protects.
  2. Safe averaging. Write a function that takes an array of Double and returns the average, but guards against the empty case so it returns an optional Double? (nil for an empty array) instead of producing nan.
  3. Overflow on purpose. Start from let big = Int.max, show that big + 1 traps, then rewrite the line with &+ and explain in a comment exactly what value the wrap-around produces and why.
  4. Inference quiz. For each of let a = 10, let b = 2.5, let c = "x", and let d = true, predict the inferred type, then confirm it by printing type(of:) for each and comparing against your prediction.