Swift Access Control
Have you ever thought about why do we need to declare something as
open? You have probably seen these keywords many times, but did you know what is actually behind them? Why do we need them? And what features do they bring?
In the present article let’s cover the next questions:
- What are the keywords
- When to use each of them?
- What are the benefits of using them?
What is Access Control?
Access control is the feature that allows us, as developers, to restrict or allow access to some parts of the code. With it, you can easily hide the implementation of specific things and allow access to the interface you want others to use.
Access Control has five different keywords that can be used not only with different types, such as structs, enums, classes, but also with initializers, properties, and methods.
Describing Access Control Levels
There are five access control levels that you can use in Swift, and now let’s cover all of them, starting with the highest one (least restrictive).
Open — allows any entity that has been declared with this keyword to be used anywhere inside the current module, but also in another module when importing the defining one.
This keyword can be used with only classes and overridable class members.
Basically, this means that if someone imports some module to another one, they can use
open classes inside of it and also subclass any class that is marked as
open. And if you are developing a framework you should consider that, because declaring a class as
open means that you considered that behavior.
Public — it is almost identical to the previous one, except that you can use it with other types and not only with classes, and you cannot subclass or override methods declared as
public in another module.
Internal — it is the default access level. It allows access to the code from anywhere in the current module, but not outside of it. So when you do not specify the access level directly, it just works like this by default.
Fileprivate — this access control level restricts the use of any entity outside of the specific file. So it is used when there is a bit of functionality that is used in a specific file and should not be accessed from another one.
Private — it is the most restrictive access level, and it restricts the use of an entity to the enclosing declaration.
Private is used when you need to hide implementation details of some functionality used inside of a single declaration.
To sum up, access control allows developers to control the access of types and things you store inside of them or methods. The default access level in Swift is
internal, and it is used even when you do not specify it directly. It is very crucial to understand this topic to be able to create good APIs with nice and easy interfaces.
Thanks for reading!
if you enjoyed this article, be sure to give it a clap so others will find it more easily.