![](/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.