简体   繁体   English

Swift:结构数组与类数组

[英]Swift: Struct Array vs Class Array

I have a swift array of struct and I am unable edit the first property, whereas I am able edit the first property with an array of class.我有一个快速的结构数组,我无法编辑第一个属性,而我可以用一个类数组编辑第一个属性。

In order to edit the first object of the struct array, I have to do [0] then .first为了编辑结构数组的第一个对象,我必须先做[0]然后.first

I know structs are valued by type, class are value by reference.我知道结构是按类型计算的,类是按引用计算的。 But I don't understand the different behavior.但我不明白不同的行为。 Can someone explain?有人可以解释吗?

class PersonObj {
    var name = "Dheearj"

}

struct Person  {
    var name = "Dheearj"
    
    mutating func update(name: String){
        self.name = name
    }
}

var array = [Person(),Person()]
array[0].update(name:"dheeraj")
array[0].name = "yuuu"
array.first?.name = "dddddd" <--- "Error Here"

var array1 = [PersonObj(),PersonObj()]
array1.first!.name = "ttt"

print(array1.first?.name ?? "")
print(array.first?.name ?? "")
print(array.count)

Screenshot of the error message:报错信息截图:

在此处输入图像描述

Mutating a struct stored within some other property behaves as though you've copied out the value, modified it, and overwrote it back into place.改变存储在某个其他属性中的结构的行为就好像您已经复制了该值,修改了它,然后将其覆盖回原位。

Take this line for example: (I replaced the optional chaining with force unwrapping, for simplicity)以这一行为例:(为简单起见,我用强制展开替换了可选链接)

array.first!.name = "dddddd"

It behaves as though you did:它的行为就像你做了:

var tmp = array.first!
tmp.name = "dddddd"
array.first = tmp

It's easy to see what that doesn't work.很容易看出什么是行不通的。 Array.first , is a get-only property (it doesn't have a setter). Array.first是一个只能获取的属性(它没有设置器)。

The case for classses works because the value stored in the array is a reference to the object, and the reference isn't changing (only the values within the object it refers to, which the array doesn't know or care about).类的情况是有效的,因为存储在数组中的值是对对象的引用,并且引用没有改变(只有它所引用的对象中的值,数组不知道或不关心)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM