美文网首页
Swift dispatch to overridden met

Swift dispatch to overridden met

作者: jetson | 来源:发表于2016-05-30 22:10 被阅读55次

    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 met

          本文链接:https://www.haomeiwen.com/subject/jztdqttx.html