Core Concepts
Structs and Classes
Learn when to use structs vs classes in Swift and how they differ in memory and behavior.
Structs vs Classes
Both can have properties, methods, and conform to protocols. Key differences:
| Feature | Struct | Class |
|---|---|---|
| Type | Value type | Reference type |
| Inheritance | No | Yes |
| Mutability | Must mark methods mutating | Mutable freely |
| Memory | Stack (usually) | Heap |
| Default init | Auto-generated | Must define |
Swift Preference: Structs
Apple recommends using structs by default. Use classes when you need:
- Inheritance
- Reference semantics (shared mutable state)
- Objective-C interoperability
Protocols
Protocols define a blueprint of methods and properties. They're the foundation of protocol-oriented programming — Swift's design philosophy.
Example
swift
// Struct (value type)
struct Point {
var x: Double
var y: Double
// Must mark method mutating if it changes properties
mutating func translate(dx: Double, dy: Double) {
x += dx
y += dy
}
func distanceTo(_ other: Point) -> Double {
let dx = x - other.x
let dy = y - other.y
return (dx * dx + dy * dy).squareRoot()
}
}
var p1 = Point(x: 0, y: 0)
var p2 = p1 // VALUE COPY
p2.x = 10
print(p1.x) // 0 - p1 unchanged!
print(p2.x) // 10
// Class (reference type)
class Dog {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func bark() -> String { return "Woof!" }
}
var dog1 = Dog(name: "Rex", age: 3)
var dog2 = dog1 // REFERENCE - same object!
dog2.name = "Max"
print(dog1.name) // Max - both changed!
// Protocol
protocol Drawable {
func draw() -> String
var color: String { get }
}
struct Circle: Drawable {
var radius: Double
var color: String
func draw() -> String {
return "Drawing \(color) circle with radius \(radius)"
}
}
let shapes: [Drawable] = [
Circle(radius: 5, color: "red"),
Circle(radius: 10, color: "blue"),
]
shapes.forEach { print($0.draw()) }Try it yourself — SWIFT