Search⌘ K
AI Features

Using Self in Swift

Explore how the self keyword is used in Swift to reference properties and methods within a class. Understand when its use is mandatory, such as in closure expressions, and when it is optional, helping you write clear and effective Swift code.

We'll cover the following...

S## The Swift self keyword

Programmers familiar with other object-oriented programming languages may be in the habit of prefixing references to properties and methods with self to indicate that the method or property belongs to the current class instance. The Swift programming language also provides the self property type for this purpose and it is, therefore, perfectly valid to write code that reads as follows:

class MyClass {
    var myNumber = 1
 
    func addTen() {
        self.myNumber += 10
    }
}

In this ...