问题描述:

I have an array of structs that I'm enumerating in reverse and when I encounter the expected element, I'd like update the element's value. Is there any way to do this while maintaining the element type as a struct?

struct MyModel {

var name

mutating func updateName(newName: String) {

self.name = newName

}

}

In another class, I have an array of my model classes declared as such:

var array: Array<MyModel> = []

I've filled up the contents of array such that its count > 0. I'd like to find elements from the tail end of the array and update them as I encounter them.

func updateElement() {

let newName = "Some Name"

let reversedArray = array.reverse()

for (index, element) in reversedArray.enumerate() {

var el = reversedArray[reversedArray.startIndex.advancedBy(index)]

el.updateName(name: newName)

}

// This does not show the array as having updated contents

print(array)

}

How can I update the array in place as I enumerate through it? I don't want to delete or insert new elements though.

网友答案:

Structs are value types. That means that they are copied when passed. You can't modify an Array of structs (Arrays are themselves structs). You create a new Array of structs that has the values you want. That's mapping. There is no such thing as updating an Array "in place" any more than there is a way to update the number 3. They're both values. (Swift has optimizations that generally make all this copying fairly cheap, but not always.)

It's very unclear why you want to do this in reverse order, but here's how you would do it:

func updateElement() {
    let newName = "Some Name"

    array = array.reverse().map {
        var element = $0
        element.updateName(newName)
        return element
    }.reverse()

    print(array)
}

This reverses the array, maps it to a new array by updating the names, then reverses it back and assigns it to the original property.

If you can explain why this is useful to do in reverse, we can probably come up with a better solution, since the double-reverse here is doing nothing useful.

网友答案:

Swift Arrays – as well as structs – are value types.

The item assigned to el is a copy of the original struct in the array, so you have to write the item back after changing it.

...
for (index, element) in reversedArray.enumerate() {
   let elIndex = reversedCmdList.startIndex.advancedBy(index)
   var el = reversedCmdList[elIndex]
   el.updateName(name: newName)
   reversedCmdList[elIndex] = el
}
...
网友答案:

The reversedArray contains copies (the structs are copied) of the elements of the original array. If you print(reversedArray) then you will see the changes. You might consider having updateElement() assign the reverseArray to the array reference.

相关阅读:
Top