简体   繁体   中英

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:

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 ?

A “mutating getter” in Swift is a property whose get block has the mutating modifier. For example, if your ProfileField looked like this:

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:

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

Even though it doesn't look like field.x modifies field , it does: it increments accessCount . That's why you must say var field to make field mutable. (For loop iterators are let by default.)

Without seeing either your ProfileField or the body of your for loop, it's impossible to say exactly why this occurs in your case. If you are not using mutating get in ProfileField itself, it may be happening in a struct nested within ProfileField .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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