Swift self Keyword

Swift self Keyword

Use self to reference the current instance, disambiguate names, and in type methods to refer to the type.


Disambiguation

Disambiguate means to make something clear or distinct.

In this instance it is used to make parameter and property names distinct from each other.

Use self to disambiguate parameter and property names.

Example

struct User {
  var name: String
  init(name: String) { self.name = name } // disambiguate
}

class Counter {
  var value = 0
  func inc() { self.value += 1 } // optional here
  class func resetAll() { print(Self.self) } // refer to the type
}


Mutating and self

Use self to disambiguate parameter and property names in mutating methods.

Example

struct Counter {
  var value = 0
  mutating func add(_ value: Int) {
self.value += value // disambiguate
} } var c = Counter() c.add(3) print(c.value)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *