2017-12-09 15 views
0

私は何か非常にシンプルなものを見逃していると感じるので、これを尋ねるのは嫌いですが、私はこの問題について私の頭をあまりにも長く叩いています。 辞書の配列内の辞書の値を更新する方法

ユーザーは、私が

func startTimer() { 

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

} //startTimer 

を押して、タイマーを開始するためのボタンをindexPath.rowと 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 } 

    } 
} 

と呼ばれる配列にtimeOnIceと呼ばれる値を格納し、私のcollectionViewのセルをタップ

2人のプレーヤーをタップすると(tappedArrayに追加)、配列は次のようになります。

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

私はこれは私がしようとした場合、行は

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

を出力するものであるtimerCounter

@objc func updateCounters() { 

    timerCounter += 1 

    for row in tappedArray { 

     print("row \(row)") 

    } 

    //Update tableview 
    tableView.reloadData() 

} //updateCounters 

を含めるように辞書にtimeOnIceを更新する方法を把握しようとしている最も困難な時間を過ごしていfor..inループの次の部分

row["timeOnIce"] = timerCounter 

私はフォローイングラム・エラー

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

私は次のようにループを変更しない限り:Dictionaryは値型はスウィフトである

答えて

1

ので

for var row in tappedArray { 

    print("row \(row)") 

    row["timeOnIce"] = timerCounter 

} 

しかし、配列に値が更新されません... forループは配列内の項目のコピーを作成します。オリジナルを更新するには、次のように配列にインデックスを使用できます。

for row in tappedArray.indices { 

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

    tappedArray[row]["timeOnIce"] = timerCounter 
} 
+0

ありがとうございます。 –

関連する問題