Swift Access Control
Access control decides which parts of your code can see and use a type, property or method. It lets you hide implementation details behind a small, clear interface, so other code cannot put your objects into an invalid state — and so you can change the internals later without breaking anyone.
The access levels
Swift's access levels are based on modules (an app target, a framework or a Swift package) and source files.
| Level | Visible from | Typical use |
|---|---|---|
open |
Any module; classes can be subclassed and overridden outside the module | Framework classes meant for subclassing |
public |
Any module (but no subclassing/overriding outside) | A library's API |
package |
Any module in the same Swift package | Shared helpers between a package's modules |
internal (default) |
Anywhere in the same module | Most app code |
fileprivate |
Only the same source file | Helpers shared by types in one file |
private |
Only the enclosing declaration (and its extensions in the same file) | Implementation details |
If you write nothing, a declaration is internal. In a single app you mostly use the default, private and fileprivate.
Hiding state with private
The classic use: keep a stored property private so it can only change through methods that enforce your rules.
struct BankAccount {
let owner: String
private var balance = 0 // nobody outside can touch this directly
init(owner: String) { self.owner = owner }
mutating func deposit(_ amount: Int) {
guard amount > 0 else { return }
balance += amount
}
mutating func withdraw(_ amount: Int) -> Bool {
guard amount > 0, amount <= balance else { return false }
balance -= amount
return true
}
func statement() -> String { "\(owner): \(balance)" }
}
var acc = BankAccount(owner: "Quang")
acc.deposit(100)
print(acc.withdraw(30))
print(acc.withdraw(500))
print(acc.statement())true
false
Quang: 70
Because balance is private, the balance can never become negative: there is no way around withdraw. Trying to access it from outside is a compile error:
struct Vault {
private var secret = "1234"
}
let v = Vault()
print(v.secret)error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:6:9: error: 'secret' is inaccessible due to 'private' protection level
1 | struct Vault {
2 | private var secret = "1234"
| `- note: 'secret' declared here
3 | }
4 |
5 | let v = Vault()
6 | print(v.secret)
| `- error: 'secret' is inaccessible due to 'private' protection level
Read-only from outside: private(set)
Often you want others to read a property but only your type to change it. Give the setter a lower access level with private(set):
struct StepCounter {
private(set) var steps = 0
mutating func walk(_ n: Int) {
steps += n
}
}
var counter = StepCounter()
counter.walk(1200)
counter.walk(800)
print("Steps today:", counter.steps) // reading is fine
// counter.steps = 0 ← error: setter is inaccessibleSteps today: 2000
private vs fileprivate
private members are visible inside the type and in its extensions in the same file. fileprivate widens that to every declaration in the file — useful when two small types in one file must cooperate.
struct Engine {
fileprivate var temperature = 90 // visible to anything in this file
private var serialNumber = "EN-77" // visible only inside Engine (+ its extensions here)
}
extension Engine {
func label() -> String { "Engine \(serialNumber)" } // allowed: same type, same file
}
struct Mechanic {
func check(_ engine: Engine) -> String {
engine.temperature > 100 ? "Overheating" : "OK at \(engine.temperature)°"
}
}
let engine = Engine()
print(engine.label())
print(Mechanic().check(engine))Engine EN-77
OK at 90°
If Mechanic tried to read engine.serialNumber, the compiler would reject it.
Note: All playgrounds on this site are a single file in a single module, so you can't observe the difference between
internal,publicandopenhere. Those levels matter when you split code into frameworks or Swift packages.
Rules that keep access consistent
Swift enforces a simple guiding principle: an entity cannot be more visible than the types it uses.
- A
publicfunction cannot take aprivatetype as a parameter or return it. - A type's members default to
internaleven if the type ispublic— you must mark API memberspublicexplicitly. - A
privatetype's members are effectively private too.
public struct Profile {
public let username: String // part of the public API
var lastLogin = 0 // internal: hidden from other modules
public init(username: String) { // public types need an explicit public init
self.username = username
}
}Tip: Start everything as
privateand widen the access level only when another piece of code actually needs it. It is easy to make something more visible later, but hard to take visibility away once others depend on it.
Test yourself
What is the default access level when you write nothing?
privatepublicinternalfileprivate
What does private(set) var steps = 0 mean?
- Nobody can read
steps - Anyone can read
steps, but only the type itself can change it stepsis a constantstepsis visible only in this file
Which level allows subclassing a class from another module?
publicopeninternalpackage