In Swift, how do `private(set)` and `internal(set)` restrict a property's setter, and what can code outside that scope still do with it?
answer
- two access levels on one property
- the getter keeps the property's level
- writes include inout and mutating calls
- the whole struct value is another matter
basics
~20 sA setter modifier gives a property's setter a lower access level than its getter. Outside that scope code can read the property, but cannot assign it, pass it inout or call a mutating member on it.
solid answer
~40 sGetters and setters normally share the property's access level; writing `fileprivate(set)`, `private(set)`, `internal(set)` or `package(set)` lowers only the setter, and it combines with the primary level, as in `public private(set) var pending`. It works on stored properties, whose synthesized setter is affected, on computed properties and on subscripts. Code that cannot reach the setter can read the value but cannot assign it, pass it as an `inout` argument or call a mutating member on it such as `append`, each reported as the setter being inaccessible. It can still call the type's own accessible mutating methods, which is how the type keeps control of its invariants. A setter cannot be more visible than its getter, and the modifier is rejected on a `let`.
code
swift · 19 linespublic struct DownloadQueue {
public private(set) var pending: [String] = [] // public getter, private setter
public internal(set) var label = "default" // public getter, internal setter
public init() {}
public mutating func enqueue(_ url: String) {
pending.append(url) // allowed: inside the type
}
}
func demo() {
var queue = DownloadQueue()
queue.enqueue("https://example.com/a.zip") // allowed: a public mutating method
queue.label = "nightly" // allowed: same module, internal setter
print(queue.pending.count) // allowed: reading is public
queue = DownloadQueue() // allowed: replaces the whole value
// queue.pending.append("b.zip") // error: setter is inaccessible
}go deeper
Recall that the getter keeps the property's level and only the setter is lowered.
Explain why assignment, inout and mutating calls such as append are all blocked, and how the type's own mutating method remains the way in.
Show where invariants really live: a struct value can be replaced wholesale, so the initializers and mutating methods must enforce them.
Decide which public state a framework exposes read-only with internal(set) or package(set) versus through explicit mutating APIs.
## A second access level for writes Every property, subscript, constant and variable has a getter and, if it is writable, a setter. By default both share the declaration's access level. Swift lets you give the **setter** a lower level with one of four modifiers written before `var` or `subscript`: - `private(set)` - `fileprivate(set)` - `internal(set)` - `package(set)` You combine it with the primary level: `public private(set) var pending: [String]` is readable from any module and writable only inside the type and its same-file extensions. It applies to stored properties too: Swift synthesizes a getter and setter for the backing storage, and the modifier lowers that synthesized setter. Two combinations are rejected: - a setter more visible than its getter, such as `private public(set) var x`, gives `private property cannot have a public setter`; - a setter modifier on a constant, such as `private(set) let limit = 3`, gives `'private(set)' modifier cannot be applied to read-only properties`. ## What code without the setter can do | Operation outside the setter's scope | Result | |---|---| | Read the property | allowed at the getter's level | | Assign it, including `+=` | `cannot assign to property: 'pending' setter is inaccessible` | | Pass it as an `inout` argument | `cannot pass immutable value as inout argument: 'pending' setter is inaccessible` | | Call a mutating member on it, such as `append` | `cannot use mutating member on immutable value: 'pending' setter is inaccessible` | | Call the owning type's accessible mutating method | allowed; the method writes from inside the type | The third row surprises people: for a value-type property, `queue.pending.append(url)` is a read-modify-write through the setter, so it is blocked exactly like an assignment. The type then offers `enqueue(_:)`, which is where validation, deduplication or notification belongs. ## Which scope `private(set)` means The setter's level follows the normal scoping rules. `private(set)` means the type's declaration and its extensions in the same file, so a free function in that file cannot write the property; use `fileprivate(set)` if file-level helpers must. `internal(set)` on a `public` property is the common framework shape: the module writes, clients read. `package(set)` lets other modules of the same package write while outside clients only read. ## What it protects and what it does not For a **struct**, `private(set)` protects the **property**, not the variable that holds the value. A caller with a `var queue: DownloadQueue` cannot write `queue.pending`, but it can replace the whole value with `queue = DownloadQueue()` or build a fresh value through any initializer it can reach. Invariants that matter therefore live in the initializers and mutating methods. For a **class**, every holder of a reference sees the same object, so a `private(set)` property is a read-only view of state the object alone changes. That includes subclasses: a subclass declared in another file, or in another module that inherits from an `open` class, cannot assign a `private(set)` property it inherits, so a base class that wants subclasses to update the value must offer a method, or choose `internal(set)` when every subclass lives in its module. A computed property can carry a setter modifier too. `public internal(set) var title: String { get { … } set { … } }` publishes the getter and keeps the setter, and whatever validation it performs, inside the module. The implicit memberwise initializer of a struct uses the property's **overall** level, not its setter's: a `private(set) var items` in an internal struct is still a parameter of the internal memberwise initializer, so code in the module can choose its initial value even though it can never assign it later. The rules for when that initializer exists belong with the material on initializers. ## Choosing the setter level 1. Expose state the type owns as `public private(set)` or `private(set)`, and offer methods for the allowed changes. 2. Use `internal(set)` or `package(set)` when collaborators inside the module or package legitimately write it. 3. Prefer a `let` when nothing should write after initialization; a setter modifier is for state that changes, only not from outside.
- Can code outside a Swift struct reset a `private(set)` property by replacing the whole struct value?Yes, if it holds the value in a `var` and can reach an initializer. `queue = DownloadQueue()` assigns the variable, not the property, so the setter's level does not apply. That is why a struct's invariants belong in its initializers and mutating methods, not only in a restricted setter.
- In Swift, does `private(set)` change the implicit memberwise initializer of a struct?No. The memberwise initializer considers the property's overall access level, not its setter's. In an internal struct, `private(set) var items: [String] = []` stays a parameter of the internal memberwise initializer, so module code can pass an initial value even though it cannot assign `items` afterwards.
A stadium scoreboard: every spectator can read the score, only the scorer's booth can change it, and a spectator who wants a different number has to go through the booth rather than reach the board.
- private(set) hides the property from reading outside the type
- Calling append on a private(set) array from outside is fine because it is a method
- A private(set) property can still be passed inout from another file
- private(set) works on let constants to make them private
- private(set) on a struct property stops callers replacing the whole value