是否可以获取以下代码来生成MyClass2:someFuncWithDefaultImplementation()被调用? protocol MyProtocol : class { func someFuncWithDefaultImplementation() func someFunc() var someInt:Int { get set }}extension MyProtocol { func
protocol MyProtocol : class { func someFuncWithDefaultImplementation() func someFunc() var someInt:Int { get set } } extension MyProtocol { func someFuncWithDefaultImplementation() { someInt = 5 } func someFunc() { someFuncWithDefaultImplementation() } } class MyClass : MyProtocol { var someInt = 6 } class MyClass2 : MyClass { func someFuncWithDefaultImplementation() { someInt = 7 } } ... let class2 = MyClass2() class2.someFunc()
MyClass2可以添加此方法:
func someFunc() { someFuncWithDefaultImplementation() }
它可以工作,但是如果MyProtocol:someFunc()除了调用someFuncWithDefaultImplementation()之外还做其他事情就没有用,因为它只是代码重复.
这样做也没有达到预期的效果:
extension MyClass2 { func someFuncWithDefaultImplementation() { someInt = 7 } }仅当符合这些协议的类未实现该方法本身时,才会调用协议中的默认实现.类的方法覆盖了协议的默认实现,而不是相反.
你可以这样做:
import UIKit protocol MyProtocol : class { func someFuncWithDefaultImplementation() func someFunc() var someInt:Int { get set } } extension MyProtocol { func someFuncWithDefaultImplementation() { someInt = 5 } func someFunc() { someFuncWithDefaultImplementation() } } class MyClass : MyProtocol { var someInt = 6 } class MyClass2 : MyProtocol { var someInt: Int = 4 func someFuncWithDefaultImplementation() { someInt = 7 } } let class2 = MyClass2() class2.someFunc()
或者像这样:
class MyClass : MyProtocol { var someInt = 6 func someFuncWithDefaultImplementation() { someInt = 8 } } class MyClass2 : MyClass { override func someFuncWithDefaultImplementation() { someInt = 7 } }
这些是我的测试所得到的,但你可能会找到更好的解决方案