Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Understand Access Control Levels in Swift
Written by Team Kodeco

In Swift, access control is used to restrict access to certain parts of your code, such as classes, structures, enumerations, properties and methods.

Swift provides four different levels of access control:

  • private: Limits access to the enclosing declaration
  • file-private: Limits access to the enclosing file
  • internal: Limits access to the enclosing module
  • public: Allows access from any source file and module

The default access level is internal, which means if you don’t specify anything, it will be set to internal.

Most of the time, this default will suffice, but there are a variety of reasons you might want to fine-tune the acces level, such as:

  • Hiding implementation details: By marking certain parts of the code as private, developers can hide the implementation details of a class or method from other parts of the codebase. This can make the code more maintainable and less prone to bugs, as it reduces the number of places that need to be changed when the implementation changes.
  • Encapsulation: By marking certain properties and methods as private, developers can ensure that they can only be accessed and modified by the class or struct that defines them. This can help enforce encapsulation, which is a fundamental principle of object-oriented programming that helps to ensure that the internal state of an object is only modified in controlled ways.
  • Modularity: By marking certain parts of the code as file-private or internal, developers can ensure that they can only be accessed from within the same module or file. This can help to make the codebase more modular and easier to understand.
  • Security: In certain cases, it may be necessary to restrict access to certain parts of the codebase for security reasons. By using private or file-private access control, developers can ensure that sensitive information or functionality can only be accessed by authorized parts of the codebase.

The rest of this section will cover each access level in more detail.

© 2024 Kodeco Inc.