简体   繁体   English

了解具有self属性的变异函数

[英]Understanding mutating functions with the self property

I'm working through Apple's Swift Programming Language book and came across the following example. 我正在研究Apple的Swift编程语言书,并遇到了以下示例。 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." 该书指出“ moveByX函数创建了一个全新的结构,其x和y值位于目标位置。”

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. 我的理解是Swift会从内存中释放值为1、1的myPoint结构,并且不再可用。 In its place a new one is created with the values 3, 3. Am I right? 取而代之的是创建一个新的值3、3。对吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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