Swift: 不能在 属性 初始化器中使用实例成员 'trialGame'; 属性 初始值设定项 运行 在 'self' 可用之前

Swift: Cannot use instance member 'trialGame' within property initializer; property initializers run before 'self' is available

在我的 Swift ViewController 中,我有代码

class ViewController: UIViewController {
    
    var camera: UIButton!
    
    var gameBrowser: UICollectionView!
    let gameBrowserReuseID = "gamecell"
    
    var games: [Game]!
    
    
    let trialGame = Game(id: "5", title: "Dog", release_date: "1989", publisher: "Nintendo", price: "20", platform: "OS X", category: "Adventure", players: ["A", "B"])
    let trialGame2 = Game(id: "5", title: "Dog", release_date: "1989", publisher: "Nintendo", price: "20", platform: "OS X", category: "Adventure", players: ["A", "B"])
    
    games = [trialGame, trialGame2]

但是,在最后一行,我收到错误“无法在 属性 初始值设定项中使用实例成员 'trialGame';属性 初始值设定项 运行 之前 'self' 可用”(第二个用于 trialGame2)。我在其他论坛上搜索了这个错误,好像这个错误一般是因为错误代码行中的一个或多个变量不能同时使用,但我不确定为什么会这样,因为我所做的只是将 class Game 的两个对象声明为常量。既然它们都在我初始化数组游戏之前就已经声明了,为什么它们都不可用?

大多数帖子建议在错误代码行前使用关键字'lazy',因此: lazy var games = [trialGame, trialGame2] 但出于某种原因,编译器告诉我需要对关键字 lazy 进行初始化。我不确定这意味着什么,编译器的唯一建议是删除关键字。

如果有帮助,这是我的游戏 class:

import UIKit

class Game: Codable {
    var id: String!
    var title: String!
    var release_date: String!
    var publisher: String!
    var price: String!
    var platform: String!
    
    var category: String!
    var players: [String]!
    
    init(id: String, title: String, release_date: String, publisher: String, price: String, platform: String, category: String, players: [String]){
        self.id = id
        self.title = title
        self.release_date = release_date
        self.publisher = publisher
        self.price = price
        self.platform = platform
        self.category = category
        self.players = players
    }
}

我在这里感到很迷茫,因为错误背后的原因和解决方案都在躲避我。感谢您的帮助!

首先,永远永远不要将属性声明为使用非可选值初始化的隐式展开的可选值。删除所有感叹号!

要回答您的问题,您不能 运行 class 中方法之外的任意代码,为什么不简单地

class ViewController: UIViewController {
    
    var camera: UIButton!
    
    var gameBrowser: UICollectionView!
    let gameBrowserReuseID = "gamecell"
    
    var games = [Game(id: "5", title: "Dog", release_date: "1989", publisher: "Nintendo", price: "20", platform: "OS X", category: "Adventure", players: ["A", "B"]),
                 Game(id: "5", title: "Dog", release_date: "1989", publisher: "Nintendo", price: "20", platform: "OS X", category: "Adventure", players: ["A", "B"])]