【swift】 タプルの配列で指定した要素のindexを取得する。


【swift】 タプルの配列で指定した要素のindexを取得します。
("学級", "名前", テストの点数)のタプル配列を testScores とします。
下記では「3年B組の田中さん」のindexを検出し、その点数(score)を40点から90点に変更します。

        typealias TestScore = (room: String, name: String, score: Int)
        var testScores = [TestScore]()
            testScores = [
            ("3年A組","佐藤",92),
            ("3年A組","田中",67),
            ("3年A組","吉田",88),
            ("3年B組","井上",45),
            ("3年B組","田中",40),
            ("3年C組","鈴木",72),
            ("3年C組","田村",61),
            ("3年C組","吉田",53)
        ]
        if let index = testScores.firstIndex(where: {$0.room == "3年B組" && $0.name == "田中"}){
            testScores[index].score = 90
            print(testScores[index])
        }
        else{
            print("該当なし")
        }

コンソールには、
(room: "3年B組", name: "田中", score: 90)
と表示され、点数が変更されていることがわかります。