Access Control Swift 3

Access control is some sort of barrier to hide the implementation details of your code and provide an interface through which code can be accessed. You might have heard of public, internal, and private, but in Swift 3, we have open, public, internal, fileprivate, and private.

It may sound quite a lot but we will cover each and every one in order from most open to most restricted:

open:

You can access open classes and class members from any source file in the defining module or any module that imports that module. You can also subclass an open class or override an open class member both within their defining module and any module that imports that module.

 

public:

public allows the same access as open  – but has more restrictive subclassing and overriding. You can only subclass and override a public class within the same module. This is important if you are writing a framework.

 

 

internal:

Internal allows use from any source file in the defining module but not from outside that module. This is generally the default access level.

 

 

fileprivate:

Fileprivate allows use only within the defining source file.

 

private:

Private allows use only from the enclosing declaration

 

Example: Getters and Setters

You can give a setter lower access than its getter to limit the read-write access.

As mentioned earlier, initially the property getter and setter is internal access. Writing private in front of property decalariation means we can only set it within the class definition, we cannot set it from another source file or from a class extension. If we wanted to be able to set the property from an extension we would need to give the setter fileprivate access.

 

Read more about Access Control Swift 3 here.

 

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.