Swift Self Detailed Explanation and Simple Example Code

  • 2021-07-24 11:50:28
  • OfStack

Use of Self in Swift

Used to disambiguate when accessing properties and calling methods.

When the parameter name of a function has the same name as its own property name, for example:


/*
 Use self Indicates whether you are accessing your own properties or parameters 
*/
class AClass {
 var greeting: String
 init(greeting: String) {
  //  Use self Distinguish attributes from parameters 
   self.greeting = greeting
 }
}

When calling its own specified constructor in a convenience constructor, for example:


 convenience init() {
   /*
    You must use the self Because according to 2 Rules for segment construction, 
    In the first 1 Before phase initialization is complete, 
    Unable to use self , 
    And because of the characteristics of object-oriented language, 
    All initialization method names are init , 
    No self The system does not know whose init
   */
   self.init()
   //  Initialize 
 }

Closure when accessing its own properties and calling its own methods, for example:


 UIView.animateWithDuration(0.25) { () -> Void in
     /*
      Closures may be thrown, and they must know who their methods and properties belong to. 
      So we have to use self
     */
     self.layoutIfNeeded()
   }

In the value type method modified by mutating, when modifying the self property, for example:


struct Point {
 var x = 0.0, y = 0.0
 mutating func moveByX(deltaX: Double, y deltaY: Double) {
   self = Point(x: x + deltaX, y: y + deltaY)
 }
}

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: