Access control in Swift

Learn about private, fileprivate, public and internal

Access Control

Use it to restrict access to parts of your code from code in another modules or files.

You can assign access levels to Classes, Structs, Enumerations in addition to their Properties, Initializers, Methods and Subscripts.

Files and Modules

Before speaking about access levels you must know the difference between File and Module.

Module is a sinle unit of code distribution that can be shipped together and imported using “import”¬†keyword such as frameworks.

File is a single Swift source code file and note that some times a file contains a definition of multiple types.

Access Levels

There are five access levels as follows.

Public access

Enables entity to be used in any source file within its defining module or any source file from other module that imports its defining module.

Class can be subclassed or overridden by subclasses within the module that defined it.

Open access

The same as Public but with the following two differences

1- It applies only to classes and class members.

2- Class with Open access can be subclassed or overridden by subclasses within the module that defined it or any other module that imports its defining module.

Internal access

Entity can be used in any source file within its defining module only.

File-Private access

Entity can be used in in its source file only.

Private access

Entity can be used within its enclosing declaration and extension to this declaration in the same source file.

Those were the five access levels where the Open access is the highest (least restrictive) and Private is the lowest (most restrictive).


Access Levels Guidelines

  • No entity can be defined in terms of another entity with more restrictive access level.
  • A function cannot have less restrictive access level than its parameters or return types.
  • By Default most entities will have Internal access unless you explicitly change that.
  • If you defined a Public custom type, its members will have Internal access by default unless you changed them.

Access Control Example Code

public class DemoPublicClass {}

internal class DemoInternalClass {}

fileprivate class DemoFilePrivateClass {}

private class DemoPrivateClass {}

 

Leave a Reply

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