Swift 2 protocol extension not calling overridden method correctly

前端 未结 3 1312
庸人自扰
庸人自扰 2020-12-09 20:46

I\'ve been running into an issue using Swift 2\'s protocol extensions with default implementations. The basic gist is that I\'ve provided a default implementation of a proto

3条回答
  •  [愿得一人]
    2020-12-09 21:34

    that is Swift's behavior. It can be good or bad, depending or your needs. Swift use static dispatch, so which method is called must be known during compilation. There are some advantages, and as usually, some disadvantages. To see, how Swift works at present time, see next very simple example. For me it looks logically ...

    protocol P {
        func foo()->Void
    }
    extension P {
        func foo()->Void {
            print("protocol foo")
        }
    }
    class A:P {
    }
    class B:A {
        func foo() {
            print("B foo")
        }
    }
    class C:B {
    
    }
    class D: C {
        // here the implementation must be overriden, 
        // due the indirect inheritance from B
        override func foo() {
            print("D foo")
        }
    }
    let a = A()      // a is A type
    a.foo()          // protocol foo
    let b = B()      // B is B type
    b.foo()          // B foo
    let p:P = B()    // p is protocol P
    // compiler is not able to know, what i would like, the dynamicType of p
    // can be everything, conforming to protocol P
    p.foo()          // protocol foo
    (p as? A)?.foo() // protocol foo
    // casting to B type, I decided, that p is B type
    (p as? B)?.foo() // B foo
    (p as? D)?.foo() // nothing is printed, becase the result of casting is nil
    
    // here the types are known at compile time
    let c = C()
    c.foo()          // B foo
    let d = D()
    d.foo()          // D foo
    let e:C = D()
    e.foo()          // D foo
    

提交回复
热议问题