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?
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
. In the init(width:height:)
set values for these properties.
Create content
as computed property that returns
the result of setupForNewGame(width:height:)
method using the above created width
and height
properties.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.