私はプロトコル拡張でいくつかのデフォルトの実装コードを与えました。しかし、この指定されたコードを、プロトコルを確認するクラスで呼び出す方法。例は次のとおりです。どのようにプロトコルのデフォルトの実装コードを迅速に呼び出しますか?
class BaseClass {}
protocol ImplementedProtocol {
func printInfo()
}
extension ImplementedProtocol where Self: BaseClass {
func printInfo() {
print("Hello! This is ImplementedProtocol")
}
}
class SuperClass: BaseClass, ImplementedProtocol {
func printInfo() {
// I should do sth here.
print("Hello! This is SuperClass")
}
}
class SubClass: SuperClass {
override func printInfo() {
super.printInfo()
print("This is SubClass")
}
}
let a = SubClass()
a.printInfo() // I get "Here is SuperClass. Here is SubClass."
// But I want "Here is ImplementedProtocol. Here is SuperClass. Here is SubClass."
が、私は信じている[この質問](のhttp:// stackoverflowの
この問題を回避するには、デフォルトの実装を提供し、任意の採用によって呼び出すことができますあなたのプロトコルに別の名前でメソッドを追加することです.com/questions/32602712/calling-protocol-default-implementation-from-regular-method)が役に立ちます。 –
SuperClassで '(self as ImplementedProtocol).printInfo()'のようなコードを使用しようとすると、SubClassの 'printInfo()'が呼び出されます。無限ループが発生します。 –