Duncan Groenewald
Duncan Groenewald

Reputation: 8988

Swift 5: How do I update values in an Array of arrays?

I am trying to update the values in an array of arrays but I guess the for item in buffer must be making a copy of the item in the buffer rather than providing a reference to the original item. Is there any way to do this other than some kind of for i=...{buffer[i][3]='Moved'}.

        var buffer = [[String]]()
        let bufRemoved = buffer.filter({$0[3] == "Removal"})
        let bufAdded   = buffer.filter({$0[3] == "Addition"})

        let moved      = bufRemoved.filter({item in bufAdded.contains(where: {$0[2] == item[2]})})

        for var item in buffer {
            if moved.contains(where: {$0[2] == item[2]}) {
                switch item[3] {
                case "Removal":
                    item[3] = "Moved(out)"
                case "Addition":
                    item[3] = "Moved(in)"
                default:
                    break
                }
            }
        }

        let bufMoved   = buffer.filter({$0[3].contains("Move")})

Upvotes: 0

Views: 1062

Answers (1)

vadian
vadian

Reputation: 285069

A solution is to enumerate the array to have also the index

    for (index, item) in buffer.enumerated() {
        if moved.contains(where: {$0[2] == item[2]}) {
            switch item[3] {
            case "Removal":
                buffer[index][3] = "Moved(out)"
            case "Addition":
                buffer[index][3] = "Moved(in)"
            default:
                break
            }
        }
    }

Upvotes: 1

Related Questions