swift语言中的结构与类 [英] structure vs class in swift language

查看:22
本文介绍了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语言中的结构与类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆