简体   繁体   中英

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? 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.

However, when initializing a subclass, the initGrid function from the base class -- not the subclass -- is run instead. This results in an array index exception since grid is empty unless the subclass creates it.

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. 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
    }
}

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.

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