1.1 · Value vs reference types
The single most load-bearing decision in a Swift API: does an assignment copy the data, or copy a pointer to shared data?
Mental model. Ask “if I hand this to someone and they change it, do I see the change?” If yes → reference. If no → value. Everything else (struct vs class vs actor) follows from that answer.
Value vs reference
What an assignment really copies, and where the bytes end up.
- What is the difference between a value type and a reference type in Swift? When do you choose each?
Value types (struct, enum, tuple) are copied on assignment and on passing into a function. Swift's compiler elides many copies, and stdlib types like Array add… - What is the difference between
struct,class, andactor?
Struct — value semantics, no inheritance, members must be mutating to change self, no deinit. Class — reference semantics, inheritance, deinit, identity via… - Where do value types live — stack or heap?
It depends on escape analysis. A small struct that does not escape is usually stored inline in its stack frame or in registers. But a struct is moved to the…
Choosing the right type
Turning the semantics into a decision you can defend in review.
- When would you still use a class in a Swift-first codebase?
Use a class when you need shared mutable identity that value copies would break: a socket, a video player, a URLSession, a cache. Also when you need deinit for… - How do you design a public Swift type: struct vs class vs actor vs enum?
Start with ownership. If copies should be independent → struct or enum. If there is one world object → class. If mutation must be serialized → actor, or a… - When is teaching “always use structs” harmful on a team?
When it produces giant mutable structs copied across threads, or when UIKit/NSManagedObject gets wrapped in cargo-cult structs that still share references…
Copy-on-write
How value types stay cheap even when they hold a lot of data.
- What is copy-on-write? Which types use it?
Copy-on-write delays the actual buffer copy until a unique reference is about to mutate. On assignment, both values point at the same heap buffer with a…
Special types
Types that tell the compiler something about control flow.
- What is
Never? Where do you see it?
Never is an uninhabited type: it has no values, so a function returning Never can never return normally. It signals “this path does not continue” — fatalError…
More in Swift language
- 1.2 · Optionals, pattern matching, control flow
- 1.3 · Protocols, extensions, associated types
- 1.4 · Generics, <code>some</code>, <code>any</code>
- 1.5 · Closures, escaping, capture lists
- 1.6 · Properties, observers, wrappers
- 1.7 · Access control
- 1.8 · Error handling, <code>defer</code>, ownership
- 1.9 · Strings and Unicode
- 1.10 · Codable, Sendable, macros, ABI
- 1.11 · Static vs dynamic dispatch