Swift
access modifiers
programming
Swift language
software development

Does Swift have access modifiers?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Swift, Apple's powerful and intuitive programming language, supports a comprehensive access control model via access modifiers. These modifiers regulate the visibility and accessibility of entities, such as classes, properties, methods, and others, within a software module. Understanding and utilizing these modifiers is crucial for robust software design and encapsulation, promoting better modularity and information hiding.

Access Levels in Swift

Swift provides five different access levels, ranging from most restrictive to least restrictive:

  1. Private
  2. File-private
  3. Internal
  4. Public
  5. Open

Here's a detailed breakdown of each access level:

Private Access

private restricts the use of an entity to its own scope, meaning it's available only within the enclosing class or struct. This makes private the most restrictive level, used when you want to hide details and functionalities that shouldn't be visible outside the scope.

swift
1class SomeClass {
2    private var privateProperty = "This is private"
3    
4    private func privateMethod() {
5        print(privateProperty)
6    }
7    
8    func accessPrivateMethod() {
9        privateMethod() // Allowed
10    }
11}
12
13let instance = SomeClass()
14// instance.privateMethod() // Not allowed

File-private Access

fileprivate is slightly less restrictive than private. It limits the use of an entity to the source file where it's defined. This can be useful to allow multiple classes or structs in the same file to access each other’s private functionality.

swift
1fileprivate class HelperClass {
2    func helperMethod() {
3        // Implementation
4    }
5}
6
7class MainClass {
8    func useHelper() {
9        let helper = HelperClass()
10        helper.helperMethod() // Allowed, same file
11    }
12}

Internal Access

internal is the default access level and allows entities to be used within any source file from the same module. This level is usually sufficient when building apps or frameworks.

swift
1struct InternalStruct {
2    var someProperty = "This is internal"
3    
4    func internalMethod() {
5        print(someProperty)
6    }
7}
8// Accessible within the same module

Public Access

public access allows entities to be used in any source file from their defining module or any module that imports the defining module. Public access is suitable for elements that you wish to expose to users of your framework.

swift
1public class PublicClass {
2    public var publicProperty = "This is public"
3    
4    public func publicMethod() {
5        print(publicProperty)
6    }
7}

Open Access

open is the least restrictive access level and applies only to classes and methods. It allows entities to be subclassed and overridden outside the module. Use this when providing APIs that are explicitly designed for extensibility.

swift
1open class OpenClass {
2    open func openMethod() {
3        // This method can be overridden outside the module
4    }
5}
6
7class Subclass: OpenClass {
8    override func openMethod() {
9        // Providing custom implementation
10    }
11}

Swift Access Levels: Key Characteristics

The table below summarizes the key characteristics of Swift's access levels:

Access LevelDescriptionApplicable ToSubclassing/ Overriding
PrivateRestricted to the enclosing declarationProperties, methods, typesNot applicable
File-privateRestricted to the source fileProperties, methods, typesNot applicable
InternalAccessible within the moduleProperties, methods, typesWithin the module
PublicAccessible from any moduleProperties, methods, typesWithin the module
OpenAccessible and extensible from any moduleClasses and methodsOutside the module

Considerations for Using Access Modifiers

  1. Encapsulation: Use access modifiers to enforce encapsulation, ensuring that implementation details of a module are hidden and protected from unintended interference.
  2. API Design: In API design, prefer more restrictive access levels and promote them only when necessary. This prevents API consumers from relying on those elements in a way that could limit future changes.
  3. Code Readability: Restrictive access levels like private or fileprivate can improve code readability by indicating which interfaces of a class or struct should be used and which parts are meant for internal working only.

Final Thoughts

Understanding and utilizing Swift's access control mechanisms can lead to more maintainable, understandable, and flexible code bases. Each access level serves a purpose, and choosing the right modifier should be a deliberate design decision instead of a default habit.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.