Self in init params

Instead of using Self or A in each of the initialisers, you can simply override each subclass’ initialiser to use its own type as operation.

This works because A‘s initialiser states that operation should be a type that conforms to A, and when you override it you have the liberty to use a subclass of A as operation instead. However, if you change operation to an unrelated type such as String or Int, the compiler will not override the existing initialiser.

Firstly, define A with its init:

class A {
    init(finishBlock: ((_ operation: A) -> Void)?) {...}
}

Now to create a subclass, you must override init using the subclass’ type as operation instead. In your call to super.init, force upcast operation ($0) to your subclass’ type, and call finishBlock with this casted operation.

class B: A {
    override init(finishBlock: ((_ operation: B) -> Void)?) {
        // Perform custom initialisation...
        super.init { finishBlock?($0 as! B) }
    }

    func fooOnlyInB() {
        print("foo")
    }
}

B‘s initialiser now passes B as operation, which means that you don’t need to cast it yourself anymore! This is thanks to the fact that you can override an init with a more specific type, in this case B.

let b = B { operation in
    operation.fooOnlyInB() // prints "foo"
}

Leave a Comment