Access controls in swift

sandeep kumar
2 min readFeb 17, 2021

Access controls help you to restrict access to parts of your code from other source files and modules

Swift access control model is based on modules and source files

Swift provides five different access level

Open. — — Highest access level

Public

Internal

File-private

Private — Lowest access level

By default when we creating an object,swift provide internal access level

Internal :

As said, Internal is the default access level for any object. That object can be accessed by any source file inside the defined module.

This Object cannot be used by any of the source files outside the defined module

Internal mainly used for single targeted apps

Private — — Lowest Access level

Restricts use of an entity only to the enclosing declaration and to the extensions of that declaration in the same file.

We can use the “Private” key for mentioning private access. Using this we can hide the implementation of a specific piece of functionality.

In the above example, I can use the “vehicleMACID” function within the class and when I try to access outside it will throw protection level.

FilePrivate:

FilePrivate restricts the use of the entity within the same source file.If we need to access an object for different classes in the same file,we can make that object as fileprivate.

Open and Public

Both Open and public is accessible is from outside the defining module. But Open can subclassable and overridable but public cant.

Open access introduced in Swift 3 and it is the Highest accessible level

Open is introduced to overcome the limitations of class inheritance in Swift.

We can apply “Open Access” only to classes and class members

--

--