swift - Swift 中的类与结构(复制)

标签 swift

我试图理解为什么结构与类有不同结果的概念。为什么这里的结果相同,但在结构上却不同:

import UIKit

class Message {
    var internalText: String  = "This is some text"
}


// create new instance

var firstMessage = Message()

//if I assign, its a reference to the original instance
var secondMessage = firstMessage

secondMessage.internalText += " with some more text added on."

//print both
print(firstMessage.internalText)
print(secondMessage.internalText)

输出:

This is some text with some more text added on.

This is some text with some more text added on.

现在,如果您将上面的声明从“class”更改为“struct”

    struct Message {
        var internalText: String  = "This is some text"
    }
...

输出变为:

This is some text

This is some text with some more text added on.

为什么在类声明中它改变了 firstMessage 对象。它们是相同的对象吗?如果我从旧对象分配一个新对象,这是一条规则吗?然后我必须声明 secondMessage = Message() 以使其成为一个新实例。 提前致谢。

最佳答案

在 Swift 中,类是引用类型,而结构是值类型。值类型在变量赋值时被复制,而引用类型则不然。

更多解释

系统将实例化的类和结构存储到内存中。内存中有两个主要部分涉及数据的存储,堆栈和堆。栈包含当前方法或函数中引入的局部变量,堆用作一种外部存储器,存储较大的值。程序只能访问存储在堆栈中的变量,因此对堆中值的引用应该保存在堆栈中。

当您使用类似Message() 的方法实例化一个类对象时,您的内存堆中会保留一个可用空间,并且对它的引用会保存在堆栈中。当您将同一个变量分配给一个新变量时,引用被复制,两个变量将引用堆中的相同字节,因此改变一个也会改变另一个。

当使用结构体时,所有的空间都保留在栈上,没有指针或引用之类的东西,所以当分配给一个新变量时,所有的数据都会被复制(事实上,系统足够聪明仅复制正在更改的必要值)。

您可以看到涵盖这些主题的精彩教程 here .

关于swift - Swift 中的类与结构(复制),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63894783/

相关文章:

ios - 关闭弹出 View

swift - Xcode 没有这样的模块 : 'PackageDescription'

swift - 完成处理程序导致不调用 deinit

swift - 使用 SwiftUI 预览崩溃 @Binding : communication with the app was interrupted

objective-c - 在 Swift 中,您将如何编写 scrollViewWillEndDragging withVelocity targetContentOffset 方法?

ios - 获取错误 "Cannot load module ' MapKit' 作为 'MapKit'“

ios - UITextView 后面的 ImageView 未剪切到边界

ios - 在 Swift 中向 UILocalNotification 添加文本字段

swift - 在 Swift 中构建字典扩展以作为值附加到数组

ios - Swift TouchBegan 导致 Xcode 崩溃,同时仍在 TouchEnded 中执行功能