简体   繁体   中英

Understanding mutating functions with the self property

I'm working through Apple's Swift Programming Language book and came across the following example. I want to make sure I have the concept correct before continuing.

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

The book states "the moveByX function creates a brand new structure who's x and y values are to the target location."

So, if I do this;

var myPoint = Point(x: 1, y: 1)
myPoint.moveByX(2, deltaY: 2)

My understanding is Swift releases the myPoint struct with the values 1, 1 from memory, and it is no longer available. In its place a new one is created with the values 3, 3. Am I right?

确切地说,将值1和1替换为3、3。在两种情况下,内存中的位置都是相同的,并且在分配特定实例时会进行分配。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM