簡體   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