1
我试图将一个协议扩展初始化器注入到现有类的指定初始化器中。如果不覆盖类中指定的初始化器,我认为没有办法绕过它,然后调用协议扩展初始化器。如何在指定的初始化器中调用协议扩展初始化器?
下面是什么我想,特别是与UIViewController
类:
class FirstViewController: UIViewController, MyProtocol {
var locationManager: CLLocationManager?
var lastRendered: NSDate?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// TODO: How to call MyProtocol initializer?
// (self as MyProtocol).init(aDecoder) // Didn't compile
}
}
protocol MyProtocol: CLLocationManagerDelegate {
var locationManager: CLLocationManager? { get set }
var lastRendered: NSDate? { get set }
init?(coder aDecoder: NSCoder)
}
extension MyProtocol where Self: UIViewController {
// Possible to inject this into initialization process?
init?(coder aDecoder: NSCoder) {
self.init(coder: aDecoder)
setupLocationManager()
}
func setupLocationManager() {
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager?.distanceFilter = 1000.0
locationManager?.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// TODO
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
// TODO
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
// TODO
}
}
有没有办法利用的协议扩展初始化,这样它就会在框架现有的初始化过程中自动调用?