Fileprivate
Closely related to private is fileprivate, which permits access to any code written in the same file as the entity, instead of the same lexical scope which private provided.
You’ll use the two new files you just created to try this out!
Right now, nothing is preventing a haphazard coder who doesn’t read the documentation from creating a Check on their own. In your safe code, you want a Check to only originate from CheckingAccount so that it can keep track of balances.
In the Check class, try adding the private modifier to the initializer:
private init(amount: Dollars, from account: CheckingAccount) { //...
While this prevents bad code from creating a Check, you’ll notice it also prevents
CheckingAccount from creating one as well. private entities can be accessed from anything within lexical scope, but in this case CheckingAccount is one step outside the scope of Check. Fortunately, this is where fileprivate is very useful.
Replace the initializer instead with fileprivate:
fileprivate init(amount: Dollars, from account: CheckingAccount) { //...
Great! Now CheckingAccount can still write checks, but you can’t create them from anywhere else.
The fileprivate modifier is ideal for code that is “cohesive” within a source file; that is, code that is closely related or serves enough of a common purpose to have shared but protected access. Check and CheckingAccount are great examples of two cohesive types.