SwiftUI 获取 UUID

SwiftUI getby UUID

我是 SwiftUI 的新手,所以我希望有人能帮助我。 我有一个 UUID,我正在尝试将内容保存到该特定对象中,但我不知道如何调用该对象,例如使用 getbyid 或其他东西。

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]
    }
}

在我的程序中使用了这段代码

@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)
}

有几种方法可以做到这一点。 None 必然是有利的,尽管第二个(带有 map)在有大量数据集的情况下可能会变慢。

请注意,在示例中,我将函数更改为接受 Binding<Game>,因为这就是您在调用站点中传递的内容。

func saveScoreToPlayer(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
    guard let index = game.wrappedValue.players.firstIndex(where: { [=10=].id == playerID }) else {
        fatalError()
    }
    game.wrappedValue.players[index].score.append(score)
}

func saveScoreToPlayer(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
    game.wrappedValue.players = game.wrappedValue.players.map {
        guard [=11=].id == playerID else { return [=11=] }
        var copy = [=11=]
        copy.score.append(score)
        return copy
    }
}

或:

func saveScoreToPlayer3(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
    guard let player = game.players.first(where: { [=12=].id == playerID
    }) else {
        fatalError()
    }
    player.wrappedValue.score.append(score)
}

您可以使用firstIndex(of:)方法获取匹配playerID的数组第一个元素的位置。

你可以试试这个:

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

Documentation