ios - Swift:在init的基类版本中调用子类函数

标签 ios swift

在 Swift 中,如何在基类的 init 方法中调用子类的函数?本质上,目标是确保每个子类调用自己版本的 initGrid,然后仅定义设置 numRowsnumCols 的所有代码一次,在基类中。

但是,在初始化子类时,将运行基类而非子类的 initGrid 函数。这会导致数组索引异常,因为 grid 为空,除非子类创建它。

class BaseGrid {
    var grid = [[NodeType]]()
    var numRows = 0
    var numCols = 0


    init() {
        // Init grid
        initGrid()

        // Set <numRows>
        numRows = grid.count

        // Set <numCols>
        numCols = grid[0].count

        // Verify each row contains same number of columns
        for row in 0..<numRows {
            assert(grid[row].count == numCols)
        }
    }


    // Subclasses override this function
    func initGrid() {}
}


class ChildGrid: BaseGrid {


    override init() {
        super.init()
    }


    override func initGrid() {
        grid = [
                [NodeType.Blue, NodeType.Blue, NodeType.Blue],
                [NodeType.Red, NodeType.Red, NodeType.Red],
                [NodeType.Empty, NodeType.Blue, NodeType.Empty]
               ]
    }

}

最佳答案

如果您要子类化并覆盖 initGrid,它将调用当前作用域中的方法。 在基类中,您可以将其留空,作为抽象。 即:

class AdvancedGrid: BaseGrid {
    override init() {
        super.init()
    }

    override func initGrid() {
        // here is you custom alghoritm
    }
}

关于ios - Swift:在init的基类版本中调用子类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29355051/

相关文章:

objective-c - 添加和删​​除单元格时如何知道 UITableView 何时完成动画

objective-c - 在 View Controller 之间拖放(包含在同一 View Controller 中)

ios - "Cannot assign to property: "任何 "is immutable"错误

ios - 无法将 SKNode 转换为 SKNode 的子类

ios - 在许多 Mac 上运行 UIAutomation 脚本?

ios - 在 Swift 类中初始化 AnyObject 属性?

ios - 如何在表格 View 中将所有单元格设置为特定大小并仅调整接收更大输入长度的单元格的大小

swift - IOS Swift 协议(protocol)不工作或遇到断点

swift - "UIApplication.sharedApplication().delegate"swift_dynamicCastClassUnconditional

ios - iOS 10 中推迟本地通知