简体   繁体   English

为什么forEach中的迭代器对于结构是不可变的,但对于类却是可变的?

[英]Why are iterators in forEach immutable for a struct but mutable for a class?

The iterator is mutable for a class: 对于一个类,迭代器是可变的:

var selections: [Selection] = []

class Selection {
    var selected: Bool

    init(selected: Bool) {
        self.selected = selected
    }
}

selections.forEach({ $0.selected = false }) // This works

but not mutable for a struct: 但对结构不可变:

var selections: [Selection] = []

struct Selection {
    var selected: Bool
}

selections.forEach({ $0.selected = false }) // This doesn't work because $0 is immutable

It is not true, that structures are immutable. 结构是不可变的是不正确的。 But you change a different instance of the structure. 但是您更改了结构的其他实例。

Swift obfuscates the way objects and structures are treated. Swift混淆了对象和结构的处理方式。

Objects are reference types, structures are value types. 对象是引用类型,结构是值类型。 That means, that iterating over objects passes a reference to the object as argument and changing the object that the reference points to, is changing the the original object. 这意味着,遍历对象将对对象的引用作为参数传递,并更改该引用指向的对象,这将更改原始对象。

Structures are value types. 结构是值类型。 A new instance of the structure is passed as argument. 该结构的新实例作为参数传递。 Moreover it is constant in this case. 此外,在这种情况下,它是恒定的。 But even if you could change this, this would not effect the original instance of the structure. 但是,即使您可以更改此设置,也不会影响该结构的原始实例。

In other programming language this different level of indirection is visible, ie in Objective-C by an * . 在其他编程语言中,这种不同级别的间接可见,即在Objective-C中由* In Swift it isn't. 在Swift中不是。

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

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