【问题标题】:Correct way to initialize class property with method用方法初始化类属性的正确方法
【发布时间】:2021-11-24 07:18:01
【问题描述】:

我正在用 Swift 做一个小游戏,但在使用类方法初始化属性时卡住了。

 class Game {
 var height: Int
 var width: Int
 var board: [[String]] = createBoard()


 init(height: Int, width: Int) {
    self.height = height
    self.width = width
 }

 func createBoard() -> [[String]]{
   var gameBoard: [[String]] = []
    //working with width and height props from above
    //filling the board and returning
   return gameBoard
  }
 }

我如何通过函数 createBoard() 设置板值? (在创建板内我正在使用高度和宽度)

【问题讨论】:

  • width 和 height 在您的示例中是 var - 您可能想要更改它们以让 - 但如果您真的打算在运行时更改棋盘大小,请添加 didSet {} 处理程序并在那里使您的游戏板无效/重新创建.

标签: swift class properties class-method


【解决方案1】:

懒惰地创建属性

好处是在第一次读取属性之前不会执行闭包

class Game {
    var height: Int
    var width: Int
    lazy var board: [[String]] = {
        var gameBoard: [[String]] = []
        //working with width and height props from above
        //filling the board and returning
        return gameBoard
    }()


    init(height: Int, width: Int) {
       self.height = height
       self.width = width
    }
 }

【讨论】:

    【解决方案2】:

    正如@vadian 所说,lazy 是一种很好的方法。不过我想补充一点。

    我认为您需要将 heightwidth 设为私有,以防止从外部更改它们,惰性块将被调用一次,如果您将更改为 ex。 height 从 10 到 100 你的棋盘计算不会被调用。如果您需要在初始化后更改游戏设置,我会建议您使用其他选项。

        class Game {
            var height: Int {
                didSet {
                    board = self.updateGameBoard(height: height,
                                                 width: width)
                }
            }
            var width: Int {
                didSet {
                    board = self.updateGameBoard(height: height,
                                                 width: width)
                } 
            }
        
            lazy var board: [[String]] = {
                return updateGameBoard(height: height, width: width)
            }()
        
            init(height: Int, width: Int) {
               self.height = height
               self.width = width
            }
    
            private func updateGameBoard(height: Int, 
                                         width: Int) -> [[String]] {
                var gameBoard: [[String]] = []
                //working with width and height props from above
                //filling the board and returning
                return gameBoard
            }
       }
    

    这将允许您通过更改 heightwidth 来更改从外部更新板的反应式

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 2019-10-24
      • 2019-10-03
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      相关资源
      最近更新 更多