简体   繁体   English

尝试快速遍历结构数组时的奇怪语法

[英]Strange syntax when try to iterate through the array of structs in swift

I have a simple array of structs 我有一个简单的结构数组

var fields: [ProfileField]?

when I try to iterate through this array, swift shows me error on this code: 当我尝试遍历此数组时,swift向我显示此代码错误:

guard let _fields = fields else {return}
for field in _fields {
}

the error is: 错误是:

Cannot use mutating getter on immutable value: 'field' is a 'let' constant

And this code compiles well: 这段代码可以很好地编译:

for var field in _fields {
}

Why do I need to declare field as var ? 为什么我需要将field声明为var

A “mutating getter” in Swift is a property whose get block has the mutating modifier. Swift中的“变异吸气剂”是一种属性,其get块具有mutating修饰符。 For example, if your ProfileField looked like this: 例如,如果您的ProfileField如下所示:

struct ProfileField {
    var accessCount: Int = 0

    var x: Int {
        mutating get {    // ← mutating getter here
            accessCount++
            return x
        }
    }
}

…then this code would generate your “Cannot use mutating getter on immutable value” error: …然后此代码将生成您的“不能在不可变值上使用变异getter”错误:

for field in _fields {
    print(field.x)
}

Even though it doesn't look like field.x modifies field , it does: it increments accessCount . 即使看起来不像field.x修改field ,它也可以做到:它会增加accessCount That's why you must say var field to make field mutable. 这就是为什么必须说var field使字段可变的原因。 (For loop iterators are let by default.) (对于循环迭代器,默认情况下是let的。)

Without seeing either your ProfileField or the body of your for loop, it's impossible to say exactly why this occurs in your case. 如果没有看到您的ProfileField或for循环的主体,就无法确切地说出这种情况的原因。 If you are not using mutating get in ProfileField itself, it may be happening in a struct nested within ProfileField . 如果您没有在ProfileField本身中使用变mutating get ,则可能是在ProfileField嵌套的结构中发生的。

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

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