如何更新字典数组中的字典值

Pau*_* S. 3 arrays dictionary swift

我不想问这个,因为我觉得我错过了一些非常简单的东西,但我一直在这个问题上纠结太久了。

当用户点击我的单元格时,我collectionView存储 indexPath.row 和一个名为timeOnIce的数组中调用的值tappedArray

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

     let cell = collectionView.cellForItem(at: indexPath) as! BenchCollectionViewCell

     if cell.cellBackgroundImageView.image == UIImage(named: "collectionviewcell_60x60_white") {

        cell.cellBackgroundImageView.image = UIImage(named: "collectionviewcell_60x60_blue")

        let currentPlayerSelected = ["indexPath": indexPath.row, "timeOnIce": 0]
        tappedArray.append(currentPlayerSelected)

     } else {

       cell.cellBackgroundImageView.image = UIImage(named: "collectionviewcell_60x60_white")

       tappedArray = tappedArray.filter { $0["indexPath"] != indexPath.row }

     }
}
Run Code Online (Sandbox Code Playgroud)

按下启动计时器的按钮

func startTimer()  {

    //start the timer
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCounters), userInfo: nil, repeats: true)

}  //startTimer
Run Code Online (Sandbox Code Playgroud)

如果两个玩家被点击(添加到tappedArray),则数组如下所示:

tappedArray [["timeOnIce": 0, "indexPath": 1], ["timeOnIce": 0, "indexPath": 0]]
Run Code Online (Sandbox Code Playgroud)

我最难的是弄清楚如何更新timeOnIce字典中的timerCounter

@objc func updateCounters() {

    timerCounter += 1

    for row in tappedArray {

        print("row \(row)")

    }

    //Update tableview
    tableView.reloadData()

}  //updateCounters
Run Code Online (Sandbox Code Playgroud)

这是行打印出来的

row ["timeOnIce": 0, "indexPath": 2]
row ["timeOnIce": 0, "indexPath": 1]
row ["timeOnIce": 0, "indexPath": 0]
Run Code Online (Sandbox Code Playgroud)

如果我在 for..in 循环中尝试以下操作

row["timeOnIce"] = timerCounter
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

`Cannot assign through subscript: 'row' is a 'let' constant`
Run Code Online (Sandbox Code Playgroud)

除非我将循环更改为以下内容:

for var row in tappedArray {

   print("row \(row)")

   row["timeOnIce"] = timerCounter

}
Run Code Online (Sandbox Code Playgroud)

但是该值不会在数组中更新...

vac*_*ama 5

因为Dictionary是 Swift 中的值类型,所以for循环会复制数组中的项。要更新原始数据,您可以像这样使用数组中的索引:

for row in tappedArray.indices {

   print("row \(tappedArray[row])")

   tappedArray[row]["timeOnIce"] = timerCounter
}
Run Code Online (Sandbox Code Playgroud)