Swift 2协议扩展没有正确调用重写方法

时间:2015-08-03 19:21:48

标签: swift swift2

我一直在使用Swift 2的协议扩展和默认实现遇到问题。基本要点是我提供了一个协议方法的默认实现,我在一个实现协议的类中重写。从基类调用该协议扩展方法,然后调用我在派生类中重写的方法。结果是没有调用重写的方法。

我试图将这个问题提炼到最小的游乐场,这说明了下面的问题。

protocol CommonTrait: class {
    func commonBehavior() -> String
}

extension CommonTrait {
    func commonBehavior() -> String {
        return "from protocol extension"
    }
}

class CommonThing {
    func say() -> String {
        return "override this"
    }
}

class ParentClass: CommonThing, CommonTrait {
    override func say() -> String {
        return commonBehavior()
    }
}

class AnotherParentClass: CommonThing, CommonTrait {
    override func say() -> String {
        return commonBehavior()
    }
}

class ChildClass: ParentClass {
    override func say() -> String {
        return super.say()
        // it works if it calls `commonBehavior` here and not call `super.say()`, but I don't want to do that as there are things in the base class I don't want to have to duplicate here.
    }
    func commonBehavior() -> String {
        return "from child class"
    }
}

let child = ChildClass()
child.say() // want to see "from child class" but it's "from protocol extension”

3 个答案:

答案 0 :(得分:7)

不幸的是,协议还没有这样的动态行为。

但是你可以通过在commonBehavior()中实施ParentClass并在ChildClass中覆盖它来实现(在类的帮助下)。您还需要CommonThing或其他类符合CommonTrait,这是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"

由于这只是您问题的简短解决方案,我希望它适合您的项目。

答案 1 :(得分:1)

为了简化我的缺乏,理解“" Yet"表示非特定错误。我发现,在覆盖扩展函数时,我似乎无法用参数编写函数,编译器给出了这样的错误,但是如果我编写一个没有参数的简单函数,并进行自定义实现,用我被覆盖的"简单功能调用它"它有效:

import Foundation
import UIKit

extension UIViewController {

    func slideInView(direction: Direction = Direction.LEFT, duration: CFTimeInterval = 0.5, closure:()->() ) {

        let animation               = CABasicAnimation(keyPath: "transform.translation.x")
        animation.fromValue         = self.view.bounds.width
        animation.toValue           = 0
        animation.duration          = 0.3
        animation.fillMode          = kCAFillModeForwards;
        animation.removedOnCompletion = false

        UIView.animateWithDuration(0.6, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
            self.view!.layer.addAnimation(animation,forKey:nil);

            }, completion: {(finished) -> () in
                closure()
        });
    }

    func slide()  {
        self.slideInView(.LEFT,duration: 0.66) {
            print("Slide in Left Complete")
        }
    }
}

class OtherUIViewController: UIViewController {



    override  func slide() {
        self.slideFromBottom(.BOTTOM,duration: 0.66) {
            print("Slide in Bottom Complete")
        }
    }

    func slideFromBottom(direction: Direction = Direction.BOTTOM, duration: CFTimeInterval = 0.5, closure:()->() ) {

        let animation               = CABasicAnimation(keyPath: "transform.translation.y")
        animation.fromValue         = self.view.bounds.height
        animation.toValue           = 0
        animation.duration          = 0.3
        animation.fillMode          = kCAFillModeForwards
        animation.removedOnCompletion = false

        UIView.animateWithDuration(0.6, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
            self.view!.layer.addAnimation(animation,forKey:nil);

            }, completion: {(finished) -> () in
                closure()
        });
    }
}

答案 2 :(得分:1)

这是斯威夫特的行为。它可能是好的,也可能是坏的,取决于您的需求。 Swift使用静态分派,因此在编译期间必须知道调用哪个方法。有一些优点,并且通常有一些缺点。要了解Swift当前的工作原理,请参阅下一个非常简单的示例。对我来说,它看起来很合理......

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