how access specifiers are works in nested levels

Generated on 8/7/2024

1 search

In Swift, access specifiers control the visibility and accessibility of code entities such as classes, structs, and their members. Here's a brief overview of how they work, especially in nested levels:

  1. Private: A declaration marked as private can only be accessed within the same file. This is the most restrictive access level.
  2. Fileprivate: Similar to private, but allows access within the same file, even if the code is in different types or extensions.
  3. Internal: The default access level if none is specified. An internal declaration can be accessed by any code within the same module.
  4. Public: A public declaration can be accessed from any module, but the internal details (like methods and properties) are not accessible unless they are also marked as public.
  5. Open: Similar to public, but also allows the class to be subclassed and methods to be overridden outside the module.

When dealing with nested types, the access level of the nested type cannot be more permissive than the access level of the type it is nested within. For example, if you have a public class with a private nested struct, the struct can only be accessed within the file that defines it.

Here's a relevant segment from the session "A Swift Tour: Explore Swift’s features and design":

"Public is one of several different access control levels available in Swift. There are also private internal and package levels. A declaration that is marked private can only be accessed by code in the same file. An internal declaration can only be accessed by other code in the same module. Whenever you don't specify an access level, Swift implicitly uses internal package declarations are accessible from other modules in the same package, and public declarations are accessible from any other module." A Swift Tour: Explore Swift’s features and design

For more detailed information, you can refer to the chapter on "Code organization" in the session "A Swift Tour: Explore Swift’s features and design".

Relevant Sessions

  1. A Swift Tour: Explore Swift’s features and design
  2. Explore Swift performance