Using Self in Swift
Learn how to use Swift's self keyword when writing object-oriented classes, and how that use differs from most of the other object-oriented programming languages.
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 context, the self
prefix indicates to the compiler that the code is referring to a property named myNumber
which belongs to the MyClass
class instance. When programming in Swift, however, it is no longer necessary to use self
in most situations since this is now assumed to be the default for references to properties and methods. “The Swift Programming Language” guide published by Apple says, “In practice you don’t need to write self in your code very often.” The function from the above example, therefore, can also be written as follows with the self
reference omitted:
func addTen() {
myNumber += 10
}
Using self in closure expressions
In most cases, the use of self
is optional in Swift. With that being said, one situation where it is still necessary to use self
is when referencing a property or method from within a closure expression. The use of self
, for example, is mandatory in the following closure expression:
document?.openWithCompletionHandler({(success: Bool) -> Void in
if success {
self.ubiquityURL = resultURL
}
})
It is also necessary to use self
to resolve ambiguity, such as when a function parameter has the same name as a class property. In the following code, for example, the first print
statement will output the value passed through to the function via the myNumber
parameter, while the second print statement outputs the number assigned to the myNumber
class property (in this case 10):
Get hands-on with 1400+ tech skills courses.