In Swift, why subclass method cannot override the one, provided by protocol extension in superclass

前端 未结 3 608
野趣味
野趣味 2021-01-05 15:06

I know the title of this question is confusing but the weird behaviour is explained in the example below:

protocol Protocol {
    func method() -> String
         


        
3条回答
  •  梦毁少年i
    2021-01-05 15:19

    The problem is that c1 and c2 are of type Protocol, as you've defined their type explicitly this way (remember: protocols are fully fledged types). This means, when calling method(), Swift calls Protocol.method.


    If you define something like:

    let c3 = SuperClass()
    

    ...c3 is of type SuperClass. As SuperClass has no more specific method() declaration, Protocol.method() is still used, when calling c3.method().


    If you define something like:

    let c4 = SubClass()
    

    ...c4 is of type SubClass. As SubClass does have a more specific method() declaration, SubClass.method() is used, when calling c4.method().


    You could also get c2 to call SubClass.method(), by down-casting it to `SubClass:

    (c2 as! SubClass).method() // returns "From Class2"
    

    Here's a demonstration on SwiftStub.

提交回复
热议问题