Canvas 访问包含对象数组的环境对象时不显示预览

Canvas preview doesn't show when accessing environmentObject containing array of objects

预览通常适用于环境对象,但在对象内访问对象数组时遇到问题。

以下视图未在预览中显示,但在模拟器中运行良好

import SwiftUI

struct ScoreCell: View {

    @EnvironmentObject var game : Game

    var player: Player

    var body: some View {
        VStack {  
            Text(String(self.game.playerScores[self.game.indexOfPlayerInScores(player: player)].totalScore()))
        }
    }
}

struct ScoreCell_Previews: PreviewProvider {
    static var previews: some View {
        ScoreCell(player: Player(name: "s", shortName: "Steph", photoURL: "steph", color: Color(.cyan)))
            .environmentObject(Game())
    }
}

如果我用硬编码索引替换它就可以正常工作(如下一行所示)

Text(String(self.game.playerScores[0].totalScore()))

附加信息:

struct PlayerScore {
    let player: Player
    var pointsList: [Int]     


    func totalScore() -> Int {
        return pointsList.reduce(0, +)
    }
}

我绝对可以在没有预览的情况下工作,但我感觉它隐藏了一个更普遍的问题,以后会困扰我...感谢您的帮助。

添加游戏代码以提供潜在信息 - 谢谢

import SwiftUI
import Combine

class Game: ObservableObject {

    var players = [Player] ()
    @Published var playerScores = [PlayerScore] ()

    func addPlayer(player: Player) {
        players.append(player)
        playerScores.append(PlayerScore(player: player, pointsList: [0]))
    }

    func addPlayer(player: Player, score: Int) {
        players.append(player)
        playerScores.append(PlayerScore(player: player, pointsList: [score]))
    }

    func indexOfPlayerInScores(player: Player) -> Int {
        return  playerScores.firstIndex(where: {[=14=].player.id == player.id})!
    }

    init () {
        self.addPlayer(player: Player(name: "Stephane", shortName: "Steph", photoURL:"steph", color: Color(.sRGB,red: 90/255, green: 197/255, blue: 191/255)))
        self.addPlayer(player: Player(name: "Sophie", shortName: "Sof", photoURL:"sof", color: Color(.sRGB, red: 189/255, green: 0/255, blue: 82/255)))
        self.addPlayer(player: Player(name: "Chloe", shortName: "Chloe", photoURL:"chloe", color: Color(.sRGB,red: 251/255, green: 78/255, blue: 84/255)))
        self.addPlayer(player: Player(name: "Stephane", shortName: "Gaby", photoURL:"gaby", color: Color(.sRGB,red: 255/255, green: 195/255, blue: 11/255)))
    }


}

肯定是这里的问题

func indexOfPlayerInScores(player: Player) -> Int {
    return  playerScores.firstIndex(where: {[=10=].player.id == player.id})!
}

Player在构造函数中没有id,所以它是自动生成的,所以上面的方法只是在运行时找不到匹配项,因为在预览中创建了播放器并且Game 中默认添加的玩家不同(独立于类型,class 或结构)。

解决方案:更改检测玩家平等的逻辑(可能明确确认为 Equatable)。