TL ; DR:
An access modifier controls who can see a member of a class. The two you'll use most are
public(anyone) andprivate(only this class).Make data
privateso callers can't break invariants. Expose what they need throughpublicmethods (often called getters and setters):class Dog { private var name: String init(_ name: String) { self.name = name } func getName() -> String { return name } }
Outside the class,
rex.nameis a compile error. Userex.getName()instead.
Full lesson:
So far every field we wrote was visible to all the code in your module (Swift's default level, internal). That's convenient, but leaks internals. If you later decide to validate or compute the value differently, every caller in the codebase breaks.
Encapsulation
Encapsulation is the idea that an object's data should be hidden behind methods. The class controls how it's read and written; outside code only sees the API.
class Account {
private var balance: Double = 0
func deposit(_ amount: Double) {
if amount < 0 { fatalError("Invalid amount") }
balance += amount
}
}
The Swift access levels
open / public | Visible everywhere, including other modules (open also allows subclassing and overriding there). |
internal | The default: visible anywhere inside the same module. |
fileprivate | Visible only inside the same source file. |
private | Visible only inside the enclosing declaration (and its extensions in the same file). |
For now, focus on public and private.
Your task
The Dog class's name field is now private. Add a func getName() -> String method that returns it.
Dog's name: RexFree plan: 30 tutor messages. PRO is unlimited.
