- Learning Swift(Second Edition)
- Andrew J Wagner
- 517字
- 2021-07-16 12:33:09
Access control
Swift provides another set of tools that helps to control what code other code has access to called access controls. All code is actually given three levels of access control:
- Private: Only accessible from within the same file
- Internal: Only accessible from within the same module or app
- Public: Accessible by any code that imports the module
Before we can really discuss this further, you should understand completely what a module is. It is beyond the scope of this book to talk about implementing a module but a module is a collection of code that can be used in other modules and apps. So far, we have used the Foundation module provided by Apple. A module is anything that you use when using the import keyword.
All code, by default, is defined to be at the internal level. That means that any given piece of code in your program can access any piece of code defined in any other file that is also included in your program as long as it follows the scoping rules we have already discussed.
As described previously, code declared as private is only accessible from the same file. This is an even better way to protect outside code from seeing code you don't want it to see. You can declare any variable or type as private by writing the private keyword before it, like this:
private var mySecretString = "Hello World" private struct MyPrivateStruct { private var privateProperty: String private func privateMethod() { } }
Note that access control is independent of the curly bracket scope. It is built on top of it. All of the existing scope rules apply, with access controls acting as an additional filter.
This is a fantastic way of improving the idea of abstractions. The simpler the outside view of your code, the easier it is to understand and use your abstraction. You should look at every file and every type as a small abstraction. In any abstraction, you want the outside world to have as little knowledge of the inner workings of it as possible. You should always keep in mind how you want your abstraction to be used and hide any code that does not serve that purpose. This is because code becomes harder and harder to understand and maintain as the walls between different parts of the code break down. You will end up with code that resembles a bowl of pasta. In the same way that it can be difficult to find where one noodle starts and ends, code with lots of interdependencies and minimal barriers between code components is very hard to make sense of. An abstraction that provides too much knowledge or access about its internal workings is often called a leaky abstraction.
Public code is defined in the same way, except that you would use the public keyword instead of private. However, since we will not study designing your own modules, this is not useful to us. It is good to know it exists for future learning but the default internal access level is enough for our apps.