简体   繁体   中英

Swift: Call some method after object initialized in protocol extension

Let's say I have structure:

class A: UIViewController {

}

class C {
}

class B: A, P {
    typealias T = C
}

protocol P: class {
    typealias T
}

extension P {
    func initP() {
        print("test")
    }
}

Is it possible to call initP without modifying B? Anything else may be modified. I'm trying to create something like generic abstract class. System (A ,P) is Base. (B, C) -- Concrete implementation. Method initP is exactly same for all implementations. That's why I'm trying to avoid calling it in implantations. On the other hand it uses methods and types from P. That's why I cannot simply call it in A. First of all I tried to make A generic but in this case App crashes in runtime if B is passed as class of the scene in storyboard

Why wouldn't this work for you:

extension P {
    init() { // Or initWithCoder since it's a ViewController?
        print("test")
        self.init()
    }
}

Since you have used a protocol extension to define initP that function will be available any time an object is known to implement the protocol.

B().initP()

let b:B
b.initP()

class C : P {
    init() {
        initP()
    }
}

class B: A, P {
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        initP()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initP()
    }
}

are all valid.

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