Swift: When we did the expansion for Int, what is the "me" within the object that was to be used?

This seems to be a bug and is resolved in Xcode 7 with Swift (2b3)

To make a convenient observation, send the code to the site, the result will be indicated by comments.

extension Int {
    var sq: Int {
        mutating get {
            self                       //5
            self = self * self         //25
            return self                //25    Here 25 is made
        }
    }
}

var n: Int = 5                         //5
n.sq                                   //25
n                                      //5      Why isn't 25?

      

My question is, if self

the getter of the property sq

refers to the integer itself, why does it n

keep 5 after n.sq

?

Let's see what happens if we just add a setter:

extension Int {
    var sq: Int {
        mutating get {
            self                       //5
            self = self * self         //25
            return self                //25    Here 25 is made
        }

        //It not making any sense, just for testing what self referring to
        set {
        }
    }
}

var n: Int = 5                         //5
n.sq                                   //25
n                                      //25     It just what we want!

      

So what's the problem in the case from above?

BTW, in this case the func like implementation sq()

would be smarter and proven, but I just want to know why it doesn't work in the getter.

>
+3


source to share


1 answer


Several solutions:

Change the line n.sq

to n = n.sq

, as the get method returns a value based on self and doesn't actually mutate it.

If you just want to use the method as you are now, write it in the extension like this:



mutating func sq() {
    self = self * self
}

      

Then you can call n.sq()

and it will do what you need

0


source







All Articles