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:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iOS4 创建后台定时器 2022-01-01
