[英]How can I compute and initialize in init “content” property ? swift
I am trying to initialize content
property by using setupForNewGame()
method where I passed two properties, but I want to use computed property, how can I do it? 我试图通过使用传递两个属性的
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 ...
}
}
Simply create properties for width
and height
in class Grid
. 只需在
class Grid
为width
和height
创建属性。 In the init(width:height:)
set values for these properties. 在
init(width:height:)
设置这些属性的值。
Create content
as computed property that returns
the result of setupForNewGame(width:height:)
method using the above created width
and height
properties. 使用上面创建的
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 ...
}
}
Usage: 用法:
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.