Introducing access control
You can add access modifiers by placing a modifier keyword in front of a property, method or type declaration.
Add the access control modifier private(set) to the definition of balance in
BasicAccount:
private(set) var balance: Dollars
The access modifier above is placed before the property declaration, and includes an optional get/set modifier in parentheses. In this example, the setter of balance is made private.
You’ll cover the details of private shortly, but you can see it in action already: your code no longer compiles!
By adding private to the property setter, the property has been made inaccessible
to the consuming code.
This demonstrates the fundamental benefit of access modifiers: access is restricted to code that needs or should have access, and restricted from code that doesn’t.
Effectively, access control allows you to control the code’s accessible interface while defining whatever properties, methods or types you need to implement the behavior you want.
The private modifier used in the brief example above is one of several access modifiers available to you in Swift:
- private: Accessible only to the defining type, which includes any and all nested types.
- fileprivate: Accessible from anywhere within the source file in which it’s defined.
- internal: Accessible from anywhere within the module in which it’s defined. This is the default access level.
- public: Accessible from anywhere within the module in which it is defined, as well as another software module that imports this module.
- open: The same as public, with the additional ability of being able to be
overridden from within another module.
Next, you will learn more about these modifiers, when to use them, and how to apply them to your code.