Swift self detailed and simple instance code _ios

Source: Internet
Author: User

Use of self in swift

The ambiguity that is generated when the method is invoked to eliminate access properties.

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


/* Use Self to indicate whether the access is either its own attribute or parameter
*
/class AClass {
 var greeting:string
 init (greeting:string) {
  // Use self to differentiate properties and parameters
   self.greeting = Greeting
 }
}

When you call its own specified constructor in a convenient constructor, for example:

 Convenience init () {/
   *
   must use self because, in accordance with the rules constructed in paragraph two,
   self cannot be used until the first phase of initialization is complete,
   and because of the attributes of the object-oriented language,
   All initialization method names are init,
   no self, and the system does not know who called Init
   /self.init ()
   //Initialization
 }

When you access your own properties and call your own methods in a closure, for example:

 Uiview.animatewithduration (0.25) {()-> Void in/
     *
     closures may be thrown, and they must know who the methods and attributes belong to,
     so use self
     /
     self.layoutifneeded ()
   }

In a value-type method modified by mutating, when the Self property is modified, 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, I hope to help you, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.