Access Control, Subscripts and Operator Overloading in Swift: Designing Clean Types

Swift 55 min min read Updated: Nov 21, 2026 Advanced
Access Control, Subscripts and Operator Overloading in Swift: Designing Clean Types
Advanced Topic 3 of 3

Access Control

LevelVisible to
privateInside the same type declaration (and its extensions in the same file)
fileprivateAnywhere in the same file
internal (default)Anywhere in the same module
publicOther modules can use it
openOther 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

  1. Make Temperature support + and <
  2. Add a safe subscript to an array wrapper that returns nil when out of range
  3. 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.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators