0

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")})
2
  • 1
    for i in buffer.indices is the way to go. Commented Jul 17, 2019 at 1:45
  • No. This is how it is in Swift. But you can compose a different updatedBuffer array, adding every item to it inside the for loop, which can be used onwards. Commented Jul 17, 2019 at 3:19

1 Answer 1

1

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
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.