Swift 2 protocol extension not calling overridden method correctly

前端 未结 3 1313
庸人自扰
庸人自扰 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条回答
  •  -上瘾入骨i
    2020-12-09 21:25

    Unfortunately protocols don't have such an dynamic behavior (yet).

    But you can do that (with the help of classes) by implementing commonBehavior() in the ParentClass and overriding it in the ChildClass. You also need CommonThing or another class to conform to CommonTrait which is then the superclass of ParentClass:

    class CommonThing: CommonTrait {
        func say() -> String {
            return "override this"
        }
    }
    
    class ParentClass: CommonThing {
        func commonBehavior() -> String {
            // calling the protocol extension indirectly from the superclass
            return (self as CommonThing).commonBehavior()
        }
    
        override func say() -> String {
            // if called from ChildClass the overridden function gets called instead
            return commonBehavior()
        }
    }
    
    class AnotherParentClass: CommonThing {
        override func say() -> String {
            return commonBehavior()
        }
    }
    
    class ChildClass: ParentClass {
        override func say() -> String {
            return super.say()
        }
    
        // explicitly override the function
        override func commonBehavior() -> String {
            return "from child class"
        }
    }
    let parent = ParentClass()
    parentClass.say()          // "from protocol extension"
    let child = ChildClass()
    child.say()                // "from child class"
    

    Since this is only a short solution for your problem I hope it fits in your project.

提交回复
热议问题