This article will show you how to access a class's private members, such as variables and methods in Swift.
In the normal case, you cannot access private members outside the scope of a class directly, but let's see what are the alternative ways to access members within and outside the scope of a class.
What is the Private Access Control?
In Swift, private is an access control used to define how types, functions, and other declarations can be accessed in your project. You can set the private accessibility (visibility) of classes, structs, enums, functions, variables, and so on.
It restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
Is there any other access controls in Swift?
Swift provides a variety of access controls that can be used for different purposes. These are open, public, internal, file-private and private.
In this guide, you will learn about private access control. Let's start.
Syntax of Private Access Control?
Following is the syntax to declare a private variable or function:
// Declare a private variable/constant
private <variableType> <variableName> = <initialValue>
// Declare a private function
private func functionName() {
// function body
}
Let's understand the above syntax:
First, you can see how to declare a private variable or constant using private keyword.
Then, you can see how to declare a private function.
How to access private members?
1. Using public methods
In Swift, you can access private properties using the public method by returning their values. Let's understand this by the example below:
// Decalring a class called Student.
class Student {
var name = ""
private var rollNumber = 0
func uniqueId() {
print(rollNumber)
}
}
// How to access it?
let alex = Student()
print("Alex Roll number: \(alex.uniqueId())") // print roll number
Explaination:
First, we have created a class Student with some variables.
Next, define a function to read the value of a private variable.
Create a class object called alex and printing his roll number.
Note: You can see, rollNumber is a private variable in the class Student, still you can read its value outside the class scope using a public function uniqueId(). Further to note, you can not access variable rollNumber directly like below:
let alex = Student()
print("Alex Roll number: \(alex.rollNumber)") // error
// here, you will get an error <'rollNumber' is inaccessible due to 'private' protection level>
2. Using Extensions
The private members of a class, structure, enum, or protocol can be accessed by creating an extension. Here's an example to help you understand:
class Student {
// private variable
private var name = "Alex John"
// private method
private func displayDetails() {
print("Full Name: \(name)")
}
}
// 1. creating object
var studentObject = Student()
// 2. access name property
print("Name:", studentObject.name)
// 3. access displayDetails() method
studentObject.displayDetails()
Explaination:
- In step 1, we created an object for the Student class.
- In step 2, we are trying to read a property called name.
- In step 3, we are calling the method displayDetails().
Notice in step 2, we are trying to read the value of a private member of the class. While we will access it, we shall get an error like the below:
error: 'name' is inaccessible due to 'private' protection level
Same error we shall get while accessing private method of the class like below:
error: 'displayDetails' is inaccessible due to 'private' protection level
How to access them?
You can access private variables and functions of a class using the extension feature provided in Swift.
** First, lets understand what an extension is in Swift.**
Extension: Using extension, you can extend a class, structure, enum, or protocol type by adding new functionality to an existing class or structure. Swift's provided classes or custom types can have additional members by using the extension keyword.
Let's see how extensions can be used to access private members by example:
class Student {
// private variable
private var firstName = "Alex"
private var lastName = "John"
private var city = "California"
private var rollNumber = "BR546"
}
extension Student {
func displayDetails() {
print("First name: \(firstName), city: \(city), and roll number: \(rollNumber)")
}
func getFullName() -> String {
"\(firstName) \(lastName)"
}
}
// 1. creating object
var studentObject = Student()
// 2. Displaying full name
let name = studentObject.getFullName()
print(name) // Alex John
Note: The extension should be in the same Swift file. Extension which defines outside the file, cannot access the private members.
3. Using computed properties
Swift provides a computed property feature through which you can access private properties.
Computed Property: A computed property, itβs all in the name, computes its property upon request. Adding a new property value based on other conditions can be a valuable addition to any of your types.
Let's understand how to access private properties using it with the example below:
class Student {
// private variable
private var firstName = "Alex"
private var lastName = "John"
// computed properties
var fullName: String {
"\(firstName) \(lastName)"
}
}
// 1. creating object
var studentObject = Student()
// 2. Displaying full name using computed property
print(studentObject.fullName)
In the above example, you can see we are printing full name of the student with the help of computed property called fullName.
4. Using lower access level with setter
You can give a setter of a lower access level than its corresponding getter, to restrict the read-write scope of that variable, property, or subscript. You assign a lower access level by writing private(set) before the var or subscript introducer.
Let's understand it by example:
class Student {
// private setter variable
private(set) var name = "Alex John"
// private method
private func displayDetails() {
print("Full Name: \(name)")
}
}
// 1. creating object
var studentObject = Student()
// 2. access name property
print("Name:", studentObject.name) // display: "Alex John"
// 3. assigning a new value
studentObject.name = "Alex Martin" // error
In the above example, you can see how to read a private member's value outside of the class scope using the private(set) setter.
It is important to note that you cannot change the value of this property as you are restricted from changing it.
Conclusion
Now you understand how to access private members of a class. There are different ways to access them in the code.
What next?
In this guide, you learned about accessing private members of a class. We encourage you to read more related topics like Access Control in Swift, Functions in Swift, etc. For more updates, stay tuned. Till then,
Eat. Sleep. Swift Anytime. Repeat.
Top comments (0)