如何更新字典数组

时间:2017-12-09 22:39:06

标签: arrays swift dictionary

我不想问这个问题,因为我觉得我错过了一些非常简单的事情,但是我已经在这个问题上喋喋不休了太长时间。

当用户点击我的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 }

     }
}

按下启动计时器的按钮

func startTimer()  {

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

}  //startTimer

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

tappedArray [["timeOnIce": 0, "indexPath": 1], ["timeOnIce": 0, "indexPath": 0]]

我正在努力弄清楚如何更新字典中的timeOnIce以包含timerCounter

@objc func updateCounters() {

    timerCounter += 1

    for row in tappedArray {

        print("row \(row)")

    }

    //Update tableview
    tableView.reloadData()

}  //updateCounters

这是行打印出来的

row ["timeOnIce": 0, "indexPath": 2]
row ["timeOnIce": 0, "indexPath": 1]
row ["timeOnIce": 0, "indexPath": 0]

如果我在for..in循环中尝试以下内容

row["timeOnIce"] = timerCounter

我收到以下错误

`Cannot assign through subscript: 'row' is a 'let' constant`

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

for var row in tappedArray {

   print("row \(row)")

   row["timeOnIce"] = timerCounter

}

但是值没有在数组中更新......

1 个答案:

答案 0 :(得分:3)

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

Dictionary