简体   繁体   English

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

[英]Swift: Invoking subclass function in base class version of init

In Swift, how can you invoke a subclass's function in the base class's init method? 在Swift中,如何在基类的init方法中调用子类的函数? Essentially, the goal is to ensure each subclass invokes its own version of initGrid , and then all the code to set numRows and numCols is defined only once, in the base class. 本质上,目标是确保每个子类都调用其自己的initGrid版本,然后在基类中仅一次定义所有设置numRowsnumCols的代码。

However, when initializing a subclass, the initGrid function from the base class -- not the subclass -- is run instead. 但是,在初始化子类时,将运行基类(而不是子类)中的initGrid函数。 This results in an array index exception since grid is empty unless the subclass creates it. 这导致数组索引异常,因为除非子类创建grid ,否则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]
               ]
    }

}

if you will subclass and override initGrid, it will call method in current scope. 如果将继承并继承initGrid,它将在当前作用域中调用method。 In base class, you can stay it empty, as abstract. 在基类中,您可以将其作为抽象保留为空。 Ie: 即:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM