Home iOS ‘self’ Keyword in Swift: What Is It, How to Use, When to use

‘self’ Keyword in Swift: What Is It, How to Use, When to use

What is "self" in Swift? What is it for? Let's figure it out!

by admin
'self' keyword in Swift: what is it, how to use it, when to use it

Today we will look at what is self keyword in Swift, what is it for, how does it work, can we replace it and many other questions.

What is ‘self’ keyword in Swift

The self keyword in Swift is a reference to the current instance of a type within the context of its instance method or computed property. It is used to differentiate between instance properties and methods, and local variables and parameters with the same name, and to call other methods and initializers of the current instance.

How to use ‘self’ keyword in Swift

Here are some examples of how you can use the self keyword in Swift:

  1. To refer to instance properties and methods: When you have a local variable or parameter with the same name as an instance property or method, you can use the self keyword to refer to the instance property or method. For example:
    class Person {
      var name: String
      var age: Int
    
      init(name: String, age: Int) {
        self.name = name // refers to the instance property name
        self.age = age // refers to the instance property age
      }
    
      func setName(name: String) {
        self.name = name // refers to the instance property name
      }
    
      func getName() -> String {
        return self.name // refers to the instance property name
      }
    }

    In this example, the self keyword is used to refer to the instance properties name and age in the initializer and the setter and getter methods. Without the self keyword, the local variables and parameters with the same names would shadow the instance properties and methods, and the code would not work as expected.

  2. To call other methods and initializers: You can use the self keyword to call other methods and initializers of the current instance. For example:
    class Person {
      var name: String
      var age: Int
    
      init(name: String, age: Int) {
        self.name = name // refers to the instance property name
        self.age = age // refers to the instance property age
      }
    
      convenience init() {
        self.init(name: "John", age: 25) // calls the initializer with two arguments
      }
    
      func sayHello() {
        print("Hello, my name is \(self.name) and I am \(self.age) years old.")
      }
    }
    

    In this example, the self keyword is used to call the initializer with two arguments from the convenience initializer. It is also used to call the sayHello method from within the class.

  3. To pass the current instance as an argument: You can use the self keyword to pass the current instance as an argument to a method or initializer. For example:
    class Person {
      var name: String
      var age: Int
    
      init(name: String, age: Int) {
        self.name = name // refers to the instance property name
        self.age = age // refers to the instance property age
      }
    
      func equals(_ other: Person) -> Bool {
        return self.name == other.name && self.age == other.age
      }
    }

    In this example, the self keyword is used to pass the current instance as an argument to the equals method. This allows the method to compare the instance properties of the current instance with those of the other instance.

It is important to note that the self keyword is optional in most cases. You do not need to use it every time you refer to an instance property or method, or call an initializer or method. However, using the self keyword can make your code more readable and easier to understand, especially if you have local variables or parameters with the same names as instance properties or methods.

When would you use ‘self’ in Swift

There are a few situations where you should use the self keyword:

  • When you have a local variable or parameter with the same name as an instance property or method, and you want to refer to the instance property or method.
  • When you want to call another initializer or method from within an initializer or method.
  • When you want to pass the current instance as an argument to an initializer or method.

It is generally a good idea to use the self keyword whenever you need to disambiguate between instance properties and methods, and local variables and parameters, or when you want to clearly indicate that you are referring to the current instance. This can make your code more self-explanatory and easier to understand.

How to replace ‘self’ in Swift

It is possible to replace the self keyword with something else, but it is not recommended. In Swift, the self keyword is a language feature that is explicitly reserved for referring to the current instance within the context of its instance method or computed property. You cannot use any other identifier as a replacement for self.

The different types of ‘self’ in Swift

There are three types of self in Swift:

  1. Implicit self

    This is the default form of self, and it is used when you do not specify the self keyword explicitly. In this case, the self keyword is implied, and you can use it to refer to the current instance without writing it out. For example:

    class Person {
      var name: String
      var age: Int
    
      init(name: String, age: Int) {
        self.name = name // refers to the instance property name
        age = age // refers to the local parameter age
      }
    }

    In this example, the self keyword is implied in the assignment self.name = name, but it is not written out. You can use the self keyword in this way whenever it is unambiguous, i.e., when there are no local variables or parameters with the same name as instance properties or methods.

  2. Explicit self

    This is the form of self that you use when you specify the self keyword explicitly. In this case, the self keyword is written out, and you can use it to refer to the current instance explicitly. For example:

    class Person {
      var name: String
      var age: Int
    
      init(name: String, age: Int) {
        self.name = name // refers to the instance property name
        self.age = age // refers to the instance property age
      }
    }

    In this example, the self keyword is written out explicitly in the assignments self.name = name and self.age = age. You can use the self keyword in this way whenever you need to disambiguate between instance properties and methods, and local variables and parameters, or when you want to clearly indicate that you are referring to the current instance.

  3. Captured self

    This is a special form of self that is used when you capture the current instance within a closure. Captured self is used to ensure that the current instance is retained and available for use within the closure. For example:

    class Person {
      var name: String
      var age: Int
    
      init(name: String, age: Int) {
        self.name = name // refers to the instance property name
        self.age = age // refers to the instance property age
      }
    
      func sayHello() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
          // captured self refers to the current instance
          print("Hello, my name is \(self.name) and I am \(self.age) years old.")
        }
      }
    }
    

    In this example, the self keyword is used to capture the current instance within the closure. Without the self keyword, the closure would not have access to the instance properties name and age, and the code would not work as expected.

You should use captured self whenever you need to retain the current instance within a closure, and you want to access its instance properties and methods from within the closure. It is important to note that captured self is different from implicit self and explicit self, and it has its own rules for how it is captured and used.

In conclusion, the self keyword in Swift is a reference to the current instance of a type within the context of its instance method or computed property. It is used to differentiate between instance properties and methods, and local variables and parameters with the same name, and to call other methods and initializers of the current instance. You should use it whenever you need to disambiguate between instance properties and methods, and local variables and parameters, or when you want to clearly indicate that you are referring to the current instance. Captured self is a special form of self that is used to retain the current instance within a closure and access its instance properties and methods from within the closure. By using self appropriately, you can make your code more readable and easier to understand.

Rate this post

Related Posts

Leave a Comment