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 - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01