Swift dispatch to overridden methods in subclass extensions

so链接
逆变

大意是extension之后override
class A: UIViewController { 
func doThing() { print("dothing super class") } 
override func viewDidLoad() { print("viewdidload superclass") super.viewDidLoad() }}
class B: A { }
extension B { 
override func doThing() { print("dothing sub class") super.doThing() } 
override func viewDidLoad() { print("viewdidload subclass") super.viewDidLoad() }}
let a: A = B()a.doThing()
let vc: UIViewController = B()
vc.viewDidLoad()

输出

dothing 
super classviewdidload
subclassviewdidload superclass

下面的答案:
首先这个A是继承自NSObject的,因为swift的class不能这么玩,

Extensions can add new functionality to a type, but they cannot override existing functionality.

但是也不应该在扩展中使用override,这应该是个bug
下面才是正确的写法

class A : NSObject {
 dynamic func doThing() { print("dothing super class") }
}
class B: A {}
extension B {
   override func doThing() {
   print("dothing sub class") 
   super.doThing()
 }
}

你可能感兴趣的:(Swift dispatch to overridden methods in subclass extensions)