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)
}
CodePudding user response:
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
}
}
CodePudding user response:
There are a few of ways you can do this. None is necessarily advantageous, although the second one (with the map) may prove slower in situations with huge data sets.
Note that in the examples I changed the function to accept Binding<Game> since that's what you are passing in in your call site.
func saveScoreToPlayer(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
guard let index = game.wrappedValue.players.firstIndex(where: { $0.id == playerID }) else {
fatalError()
}
game.wrappedValue.players[index].score.append(score)
}
or
func saveScoreToPlayer(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
game.wrappedValue.players = game.wrappedValue.players.map {
guard $0.id == playerID else { return $0 }
var copy = $0
copy.score.append(score)
return copy
}
}
or:
func saveScoreToPlayer3(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
guard let player = game.players.first(where: { $0.id == playerID
}) else {
fatalError()
}
player.wrappedValue.score.append(score)
}
