简体   繁体   English

我如何计算和初始化init的“ content”属性? 迅速

[英]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 Gridwidthheight创建属性。 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. 使用上面创建的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 ...
    }
}

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.

相关问题 Swift init()中不可变字典类型的Initialize属性 - Initialize property of type immutable dictionary in Swift init() 如何在 Swift 中初始化 Realm 配置? - How can I initialize a Realm configuration in Swift? 如何在 Swift 中初始化结构或 class? - How can I initialize a struct or class in Swift? 如何使用共享的init方法初始化let变量? - How can I initialize a let variable using a shared init method? 我如何快速从一个类中初始化一个元组属性? - How do i init a tuple property from a class in swift? 如何将不可变的Swift属性初始化为计算值? - How do I initialize an immutable Swift property to a computed value ? Swift类中的错误:super.init调用时未初始化属性-如何初始化需要在其初始值设定项参数中使用self的属性 - Error in Swift class: Property not initialized at super.init call - How to initialize properties which need use of self in their initializer parameter 如何计算 Swift 中的 SHA512/256 hash? - How can I compute the SHA512/256 hash in Swift? 我无法迅速在super.init()之前或之后初始化事物 - In swift I cant initialize things before the super.init() or after 如何在UIAlertController中为swift覆盖便利init? - How can I override convenience init in UIAlertController for swift?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM