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

前端 未结 3 615
野趣味
野趣味 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条回答
  •  梦谈多话
    2021-01-05 15:28

    I'm not quite sure of the underlying mechanism but it must be something to do with the fact that protocols don't necessarily allow for inheritance.

    One way to work around this problem is by also adding the method to SuperClass

    import Foundation
    protocol Protocol: class {
        func method() -> String
    }
    
    extension Protocol {
        func method() -> String {
            return "From Base"
        }
    }
    
    class SuperClass: Protocol {
        func method() -> String {
            return "From Super"
            }
    }
    
    class SubClass: SuperClass {
        override func method() -> String {
            return "From Class2"
        }
    }
    
    let c1: Protocol = SuperClass()
    c1.method() // "From Super"
    let c2: Protocol = SubClass()
    c2.method() // "From Class2"
    

提交回复
热议问题