Swift 5:如何更新数组中的值?

时间:2019-07-17 01:40:14

标签: arrays swift swift5.1

我正在尝试更新数组数组中的值,但是我猜for item in buffer必须在缓冲区中复制该项目,而不是提供对原始项目的引用。除了某种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")})

1 个答案:

答案 0 :(得分:1)

一种解决方案是让enumerate数组也具有索引

    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
            }
        }
    }