繁体   English   中英

我如何计算和初始化init的“ content”属性? 迅速

[英]How can I compute and initialize in init “content” property ? swift

我试图通过使用传递两个属性的setupForNewGame()方法来初始化content属性,但是我想使用计算属性,该怎么办?

class Grid{
   private var content: [[Int?]]
   init(width: Int, height: Int){
      content = Grid.setupForNewGame(width: width, height: height)
   }
   class func setupForNewGame(width: Int,height: Int)->[[Int]]{
      return ...
   }
}

只需在class Gridwidthheight创建属性。 init(width:height:)设置这些属性的值。

使用上面创建的widthheight属性, returns content创建为计算属性 ,该content returns setupForNewGame(width:height:)方法的结果。

class Grid {
    let width: Int
    let height: Int

    var content: [[Int]] { //this is a computed property.....
        return Grid.setupForNewGame(width: self.width, height: self.height)
    }

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

    class func setupForNewGame(width: Int, height: Int) -> [[Int]] {
        return ...
    }
}

用法:

let grid = Grid(width: 3, height: 3)
print(grid.content) //prints the result returned from `setupForNewGame(width:height:)` method using width = 3 and height = 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM