Access Control, Subscripts and Operator Overloading in Swift: Designing Clean Types
Access Control
| Level | Visible to |
|---|---|
| private | Inside the same type declaration (and its extensions in the same file) |
| fileprivate | Anywhere in the same file |
| internal (default) | Anywhere in the same module |
| public | Other modules can use it |
| open | Other modules can use and subclass it (classes) |
swift
struct BankAccount {
private(set) var balance: Double = 0 // readable outside, writable only inside
mutating func deposit(_ amount: Double) {
guard amount > 0 else { return }
balance += amount
}
}
var acc = BankAccount()
acc.deposit(50)
acc.deposit(-10)
print(acc.balance)
Output
50.0
Why hide? Hiding details lets you change the inside later without breaking the code that uses your type, and it prevents misuse such as setting a balance directly.
Subscripts
swift
struct Grid {
let rows: Int, cols: Int
private var cells: [Int]
init(rows: Int, cols: Int) {
self.rows = rows; self.cols = cols
cells = Array(repeating: 0, count: rows * cols)
}
subscript(row: Int, col: Int) -> Int {
get { cells[row * cols + col] }
set { cells[row * cols + col] = newValue }
}
}
var g = Grid(rows: 2, cols: 3)
g[1, 2] = 9
print(g[1, 2], g[0, 0])
Output
9 0
Operator Overloading
swift
struct Vector {
var x: Double, y: Double
static func + (a: Vector, b: Vector) -> Vector { Vector(x: a.x + b.x, y: a.y + b.y) }
static func * (v: Vector, k: Double) -> Vector { Vector(x: v.x * k, y: v.y * k) }
static prefix func - (v: Vector) -> Vector { Vector(x: -v.x, y: -v.y) }
}
let a = Vector(x: 1, y: 2), b = Vector(x: 3, y: 4)
print(a + b, a * 3, -a)
Output
Vector(x: 4.0, y: 6.0) Vector(x: 3.0, y: 6.0) Vector(x: -1.0, y: -2.0)
Use operators sparingly Overload an operator only when its meaning is obvious, such as
+ for vectors. A clear method name is better than a clever symbol.
Common Mistakes
- Making everything public
- Exposing mutable state that should be
private(set) - Creating custom operators nobody can read
Practice
- Make
Temperaturesupport+and< - Add a safe subscript to an array wrapper that returns nil when out of range
- Hide a cache property with
private
Conclusion
Good types hide details, offer natural access with subscripts and operators, and keep a small public surface.
Quick Summary: Access levels; private(set); subscripts; operators.

