structure vs class in swift language(swift语言中的结构与类)
问题描述
来自苹果书结构和类之间最重要的区别之一是结构在代码中传递时总是被复制,但类是通过引用传递的."
From Apple book "One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference."
谁能帮我理解这意味着什么?对我来说,类和结构似乎是一样的.
Can anyone help me understand what that means? To me, classes and structs seem to be the same.
推荐答案
这是一个带有 class
的示例.请注意,更改名称时如何更新两个变量引用的实例.Bob
现在是 Sue
,在任何曾经引用过 Bob
的地方.
Here's an example with a class
. Note how when the name is changed, the instance referenced by both variables is updated. Bob
is now Sue
, everywhere that Bob
was ever referenced.
class SomeClass {
var name: String
init(name: String) {
self.name = name
}
}
var aClass = SomeClass(name: "Bob")
var bClass = aClass // aClass and bClass now reference the same instance!
bClass.name = "Sue"
println(aClass.name) // "Sue"
println(bClass.name) // "Sue"
现在有了一个struct
,我们看到值被复制了,每个变量都保留了它自己的一组值.当我们将名称设置为 Sue
时,aStruct
中的 Bob
结构体不会改变.
And now with a struct
we see that the values are copied and each variable keeps it's own set of values. When we set the name to Sue
, the Bob
struct in aStruct
does not get changed.
struct SomeStruct {
var name: String
init(name: String) {
self.name = name
}
}
var aStruct = SomeStruct(name: "Bob")
var bStruct = aStruct // aStruct and bStruct are two structs with the same value!
bStruct.name = "Sue"
println(aStruct.name) // "Bob"
println(bStruct.name) // "Sue"
因此,对于表示有状态的复杂实体,class
非常棒.但是对于只是测量值或相关数据位的值,struct
更有意义,因此您可以轻松地复制它们并使用它们进行计算或修改值而不必担心副作用.
So for representing a stateful complex entity, a class
is awesome. But for values that are simply a measurement or bits of related data, a struct
makes more sense so that you can easily copy them around and calculate with them or modify the values without fear of side effects.
这篇关于swift语言中的结构与类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:swift语言中的结构与类


基础教程推荐
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01