Structs, Classes and Protocols
Harry
· 16 Sep 2026
· 14 views
Log in to track your progress and mark lessons complete.
Sponsored
Structs are value types
A struct groups related data and behaviour, and it is a value type: copying it makes an independent copy. Swift favours structs for most models.
struct Point {
var x: Int
var y: Int
func distanceToOrigin() -> Double {
Double((x*x + y*y)).squareRoot()
}
}
var a = Point(x: 3, y: 4)
var b = a // a full copy
b.x = 99 // does NOT change a
Classes are reference types
A class looks similar but is a reference type: copies share the same underlying object, and classes support inheritance. Use classes when you need shared, mutable state or identity.
Protocols: contracts
A protocol defines a set of requirements a type promises to fulfil – like an interface. Protocol-oriented design is core Swift style:
protocol Describable {
var summary: String { get }
}
struct Book: Describable {
let title: String
var summary: String { "Book: (title)" }
}
Anything that conforms to Describable can be used wherever a Describable is expected.
Key points
- Structs are value types (copied); prefer them for models.
- Classes are reference types (shared) and support inheritance.
- Protocols define capabilities that many types can adopt.
- Swift favours composition with protocols over deep class hierarchies.