Self keyword
Definition and use
Self keyword
Definition and use
0
0
Checkbox to mark video as read
Mark as read

In Swift, the self keyword refers to the current instance of the class, struct, or enum in which the code is running. It is used to access properties, methods, and functions of the current instance, and to distinguish between instance properties and parameters or local variables that may have the same name.

Common Uses of self in Swift

  • Disambiguation: When a method or initializer has a parameter with the same name as a property, self is used to differentiate between the two.
  • Within closures: Closures can capture and reference self, especially when dealing with memory management or asynchronous code.
  • Initializer: self is often used inside initializers to set instance properties.

Example: Disambiguation

class Person {
    var name: String
    
    init(name: String) {
        self.name = name  // self.name refers to the instance property, name refers to the parameter
    }
    
    func printName() {
        print("My name is \(self.name)")
    }
}

let person = Person(name: "John")
person.printName()  // Output: My name is John

In this example, the self keyword is used to clarify that we are referring to the name property of the class and not the parameter in the initializer.

Usage in Closures

When using closures, specially asynchronously, self is required to make it clear that the closure is capturing the instance, which helps avoid retain cycles in some cases.

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy