Search code examples
iosswiftuiuuid

SwiftUI getby UUID


I'm pretty new to SwiftUI so I'm hoping someone can help me out here. I have a UUID and I am trying to save content into that specific object, but I do not know how to call the object, like with a getbyid or something.

struct Game: Identifiable, Codable {
    let id: UUID
    var title: String
    var players: [Player]
}
extension Game {
    struct Player: Identifiable, Codable {
        let id: UUID
        var name: String
        var score: [Int32]
    }
}

used this code in my program

@Binding var game: Game
saveScoreToPlayer(game: $game, playerID: player.id, score: Int32)

func saveScoreToPlayer(game: Game, playerID: Game.Player.ID, score: Int32) {
    //save score to player obviously doesn't work
    game.playerID.insert(score at:0)
}

Solution

  • You can use the firstIndex(of:) method to get the position of the first element of the array that matches playerID.

    You can try this:

    func saveScoreToPlayer(game: Game, playerID: Game.Player.ID, score: Int32) {
        if let index = game.players.firstIndex(where: { $0.id == playerID }) {
            game.players[index].score.insert(score, at: 0)
        } else {
            // handle error here
        }
    }
    

    Documentation