2017-04-01 5 views
0

私はプロトコル拡張でいくつかのデフォルトの実装コードを与えました。しかし、この指定されたコードを、プロトコルを確認するクラスで呼び出す方法。例は次のとおりです。どのようにプロトコルのデフォルトの実装コードを迅速に呼び出しますか?

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." 
+1

が、私は信じている[この質問](のhttp:// stackoverflowの

この問題を回避するには、デフォルトの実装を提供し、任意の採用によって呼び出すことができますあなたのプロトコルに別の名前でメソッドを追加することです.com/questions/32602712/calling-protocol-default-implementation-from-regular-method)が役に立ちます。 –

+1

SuperClassで '(self as ImplementedProtocol).printInfo()'のようなコードを使用しようとすると、SubClassの 'printInfo()'が呼び出されます。無限ループが発生します。 –

答えて

0

プロトコルは、特定のメソッドとプロパティを持つコンパイル時の保証に似ています。デフォルトの実装では、プロトコルの採用者にインプリメンテーションを注入することで、これにもう一つの複雑さが加わります。私はSwiftのソースコードを習得するスキルは持っていませんが、アダプターが独自の実装を提供する場合、デフォルトの実装は影が薄く、戻す方法はないと思います。

protocol ImplementedProtocol { 
    func printInfo() 

    func defaultPrintInfo() 
} 

extension ImplementedProtocol where Self: BaseClass { 
    func printInfo() { 
     defaultPrintInfo() 
    } 

    func defaultPrintInfo() { 
     print("Hello! This is ImplementedProtocol") 
    } 
} 

class SuperClass: BaseClass, ImplementedProtocol { 
    func printInfo() { 
     self.defaultPrintInfo() 
     print("Hello! This is SuperClass") 
    } 
} 
+0

私のアイデアは素早く優先するコードスタイルではないので、 'ImplementedProtocol'から継承したクラスに対して同様のコードを実装する必要がありますが、実装を' ImplementedProtocol'から 'SuperClass'に移すことに決めました。ご回答有難うございます。 –

関連する問題