Table of contents
1.
Introduction
2.
Types of Swift Access Control
3.
Public Access Control
4.
Private Access Control
5.
Fileprivate Access Control
6.
Internal Access Control
7.
Frequently Asked Questions
7.1.
Which of the access specifiers must be used for main() method?
7.2.
Which access control is used as a default for a member of a class if no access specifier is used for it?
7.3.
What is the process by which we can control what parts of a program can access the members of a class?
7.4.
How can a protected modifier be accessed?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Swift Access Control

Author SAURABH ANAND
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Access control is used to restrict access to code blocks, modules, and abstraction. Access control techniques can access classes, structures, and enumerations based on their properties, methods, initializers, and subscripts. Through access control, constants, variables, and functions in a protocol are controlled and permitted access as global and local. Entities are access controls applied to properties, types, and methods.

This blog will teach us about Swift access control, its many types, and how to apply them with examples.

Let’s see an example of swift access control.

class car {
  public func type1() {...}
  private func type2() {...}
}

 

Here,

type1() is public i.e. it can be accessed by other classes.

type2() is private i.e. it can not be accessed by other classes.

Note the keyword public and private. These are access controls in Swift.

Types of Swift Access Control

Swift includes four access controls:

Controls

Description

public declarations are accessible from everywhere 
private declarations are accessible only within the defined class or struct
fileprivate declarations are accessible only within the current swift file
internal  declarations are accessible only within the defined module (default)

Public Access Control

When we declare methods, properties, classes, and so on as public in Swift, we can access them from anywhere. The scope of the public access modifier is unrestricted. As an example,

class cows {
  // Public property
  public var legs: Int = 0
  
  // Public method
  public func display() {
    print("Cow is a domestic animal.");
    print("Total Legs of cows:", legs)
  }
}

// Creating an object
var obj = cows()

// Accessing and assigning value to public property
obj.legs = 4

// Accesing public method
obj.display()


Output

Cow is a domestic animal.
Total Legs of cows: 4

 

In the above example, we have created a class named cows with two public data members: legs and display().

We have then created an object of cows class named obj. We then access the public data members directly by using the codes obj1.legs and obj1.display().

Private Access Control

When a type member is declared private, it can only be accessed within the same class or struct. As an example,

class Student {
 // Private property
 private var name = "coding ninjas"
 
 // Private method    
 private func display() {
   print("Hello!!")
 }
}

var student1 = Student()
// Access name property
print("Name:", student1.name)

// Access display() method 
student1.display()

 

Error

error: 'name' is inaccessible due to 'private' protection level
print("Name:", student1.name)
error: 'display' is inaccessible due to 'private' protection level
student1.display()


In the above example, we have created a class named Student with a property name and a method display(). 

We can't access name or display() outside of Student because they're marked as private. The code will throw the following error in this case.

Fileprivate Access Control

When a type member is declared as fileprivate, it can only be accessed from within the specified source file. As an example,

class company {
// fileprivate property
fileprivate var name = "Coding ninjas"

// fileprivate method
fileprivate func display() {
 print("Hello!!")
 }
}

// Create object of company class
var employee1 = company()

// Access name property
print("Name:", employee1.name)

// Access display method 
employee1.display()

 

Output

Name: Coding ninjas
Hello!!


We created the fileprivate data members name and display() inside the company class in the preceding example.

Because the name and display() data members are declared as fileprivate, they can be accessed from anywhere in the source file.

 

Note: If we try to access the fileprivate data members from another Swift file, we'll get an error.

Internal Access Control

When a type or type member is declared internal, it can only be accessed within the same module.

A module is made up of different types (classes, protocols, and so on) and resources (data). They're designed to work together as a logical functional unit.

class company {
// define internal property
internal var name = "coding ninjas"
}

// Create object of company class
var company1 = company()

// Access name property
print("Name:", company1.name)

 

Output

Name: coding ninjas

 

We created a class named company with a property name in the preceding example. We can access name outside the class because it is internal, and they are both in the same module.

Internal is similar to the public access modifier when used within a single module.

Frequently Asked Questions

Which of the access specifiers must be used for main() method?

main() method must be specified public.

Which access control is used as a default for a member of a class if no access specifier is used for it?

Private access control must be used because When we pass an argument through call-by-value, a copy of the argument is placed in the formal parameter of the subroutine, and changes to the subroutine's parameters have no effect on the original argument, which remains unchanged.

What is the process by which we can control what parts of a program can access the members of a class?

Encapsulation is the process by which we can control what parts of a program can access the members of a class.

How can a protected modifier be accessed?

The protected access modifier can be used both inside and outside of the package, but only by inheritance. With data members, methods, and constructors, the protected access modifier can be applied. It isn't possible to use it in class.

Conclusion

In this article, we have extensively discussed the concept of the Swift access control. We started with the introduction of Swift access control, and types of Swift access control.

After reading about the Swift access control, are you not feeling excited to read/explore more articles on the topic of Swift? Don't worry; Coding Ninjas has you covered. To learn, see  Swift Syntax and ProgramSwift continue and fallthrough statements, and Swift Environment setup.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your capacity in coding, you may check out the mock test series and participate in the contests hosted on the Coding Ninjas Studio website. But if you have just started learning and are looking for questions asked by tech giants like Amazon, Microsoft, Google, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

You may also consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass