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:
- Private: A declaration marked as
private
can only be accessed within the same file. This is the most restrictive access level. - Fileprivate: Similar to
private
, but allows access within the same file, even if the code is in different types or extensions. - Internal: The default access level if none is specified. An
internal
declaration can be accessed by any code within the same module. - 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 aspublic
. - 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
Explore Swift performance
Discover how Swift balances abstraction and performance. Learn what elements of performance to consider and how the Swift optimizer affects them. Explore the different features of Swift and how they’re implemented to further understand the tradeoffs available that can impact performance.
A Swift Tour: Explore Swift’s features and design
Learn the essential features and design philosophy of the Swift programming language. We’ll explore how to model data, handle errors, use protocols, write concurrent code, and more while building up a Swift package that has a library, an HTTP server, and a command line client. Whether you’re just beginning your Swift journey or have been with us from the start, this talk will help you get the most out of the language.