Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
mobile development

How to use the self keyword in Swift

Muhammad Saad Mehmoon

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In Swift, the self keyword is mainly used to refer to the current instance of a class. It is used within classes, structs, and enumerations. Following are the different instances of when the self keyword is used.

Initializers of a class

The self keyword is used within the initializers (the init() method) of a class to differentiate property names from argument names. However, if the argument names are different from the class property names, the self keyword is not needed.

Code example

Take a look at the following code example:

class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let testPerson = Person(name: "Saad", age: 18)
print(testPerson.name, testPerson.age)
Code example to show the use of the self keyword within classes

Explanation

In the above example, the Person class has property names age and name, while the init() method also has arguments with the same names. Therefore, it is necessary to use the self keyword to tell the compiler which variable name refers to the argument and which refers to the actual class property.

Closures within a class

Closures are self-contained blocks of code that can be used elsewhere in the code. The self keyword is required when dealing with closures within a class.

Code example

Consider the following code example:

class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
var info: () -> String {
return {
"\(self.name) is \(self.age) years old."
}
}
}
let testPerson = Person(name: "Ali", age: 20)
print(testPerson.info())
Code to show the use of self in a closure within a class

Explanation

In the above example, the variable info defines a closure that returns a string with the name and age of the person. It is necessary to use the self keyword here to explicitly tell the compiler that it is referring to the class property variables.

Enumeration cases

Enumeration, also known as enum, is a user-defined data type that contains related values. The self keyword is used in a function within an enum to perform an action based on the case.

Code example

Take a look at the following code:

enum Health {
case healthy, sick, deceased
func info() -> String {
switch self {
case .healthy:
return "You're healthy"
case .sick:
return "You're sick. Please go to a doctor"
case .deceased:
return "You're dead? RIP"
}
}
}
let personOneHealth = Health.sick
print(personOneHealth.info())
let personTwoHealth = Health.deceased
print(personTwoHealth.info())
Code to show the use of self within enumerations

Explanation

In the above example, the self keyword used in line 7 tells the compiler that the switch statement refers to the current instance of that enum.

Extensions

Extensions are used to add additional functionality to an existing type (this includes classes, too). However, they cannot override any existing functionality. The self keyword is used in an extension to perform an action on an instance of that particular type.

Code example

The following code uses a simple example to demonstrate the use of self in an extension:

extension Int {
func cubed() -> Int {
return self * self * self
}
}
let testInt: Int = 3
print("The cube of", testInt, "is", testInt.cubed())
Code to demonstrate the use of self in an extension

Explanation

In the above example, the type Int is extended, and another function called cubed() is added, which returns the cube of the value stored in an Int instance. The self keyword is used in line 3 to access the value of the current instance.

RELATED TAGS

swift
mobile development

CONTRIBUTOR

Muhammad Saad Mehmoon
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring