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

查看:26
本文介绍了Swift 语言中的结构与类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自苹果书结构和类之间最重要的区别之一是结构在代码中传递时总是被复制,而类是通过引用传递的."

谁能帮我理解这意味着什么?对我来说,类和结构似乎是一样的.

解决方案

这是一个带有 class 的示例.请注意当名称更改时,两个变量引用的实例如何更新.Bob 现在是 Sue,任何地方都引用了 Bob.

class SomeClass {变量名:字符串初始化(名称:字符串){self.name = 姓名}}var aClass = SomeClass(name: "Bob")var bClass = aClass//aClass 和 bClass 现在引用同一个实例!bClass.name = "苏"println(aClass.name)//"苏"println(bClass.name)//"苏"

现在使用 struct 我们看到值被复制并且每个变量保持它自己的一组值.当我们将名称设置为 Sue 时,aStruct 中的 Bob 结构不会改变.

struct SomeStruct {变量名:字符串初始化(名称:字符串){self.name = 姓名}}var aStruct = SomeStruct(name: "Bob")var bStruct = aStruct//aStruct 和 bStruct 是两个具有相同值的结构体!bStruct.name = "苏"println(aStruct.name)//"鲍勃"println(bStruct.name)//"苏"

因此对于表示有状态的复杂实体,class 非常棒.但是对于仅仅是测量值或相关数据位的值,struct 更有意义,这样您就可以轻松地复制它们并使用它们进行计算或修改值,而无需担心副作用.>

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.

解决方案

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"

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"

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天全站免登陆