![](/img/trans.png)
[英]Initialize property of type immutable dictionary in Swift init()
[英]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 Grid
為width
和height
創建屬性。 在init(width:height:)
設置這些屬性的值。
使用上面創建的width
和height
屬性, 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.