Swift - Custom Type self Property

Introduction

Every instance of a class has an implicit property known as self.

The self property refers to the instance of the class.

Recall from earlier the property named speed:


class Truck {
  var speed = 0

  func accelerate() {
     speed  += 10
     if speed  > 80 {
        speed  = 80
     }
     printSpeed()
  }
...

Because speed is declared within the class, you can also rewrite the preceding by prefixing speed with self :

class Truck {
   var speed = 0

   func accelerate() {
      self.speed  += 10
      if self.speed  > 80 {
         self.speed  = 80
      }
      printSpeed()
   }
   ...

In most cases, prefixing a property using the self keyword is redundant.

However, there are cases for which this is actually useful and mandatory.

Consider the following example:

class Truck {
   var speed = 0

   func setInitialSpeed(speed: Int) {
      self.speed = speed
   }
   ...

Here, the parameter name for the setInitialSpeed() method is also named speed, which is the same as the property named speed.

To differentiate between the two, you use the self keyword to identify the property.