プロトコルとプロトコル拡張を迅速に理解するのに苦労しています。
クラスに適用できる一連のプロトコルと、デフォルトの実装を提供する一連のプロトコル拡張を定義したいと考えています。コード例:
// MARK: - Protocols & Protocol Extensions
protocol OutputItem {
typealias ResultType
func rawValue() -> ResultType
// other requirements ...
}
protocol StringOutputItem : OutputItem {}
extension StringOutputItem {
typealias ResultType = String
override func rawValue() -> Self.ResultType {
return "string ouput"
}
}
protocol IntOutputItem: OutputItem {}
extension IntOutputItem {
typealias ResultType = Int
override func rawValue() -> Self.ResultType {
return 123
}
}
rawValue()
拡張機能の上記のオーバーライド関数はエラーを返しますAmbiguous type name 'ResultType' in 'Self'
。Self
からを削除するとSelf.ResultType
、エラーが発生します'ResultType' is ambiguous for type lookup in this context
。
どのタイプを使用するかをプロトコル拡張に通知するにはどうすればよいResultType
ですか?
私の目的は、次のようにプロトコルとその拡張機能をクラスに適用できるようにすることです。
// MARK: - Base Class
class DataItem {
// Some base class methods
func randomMethod() -> String {
return "some random base class method"
}
}
// MARK: - Subclasses
class StringItem : DataItem, StringOutputItem {
// Some subclass methods
}
class AnotherStringItem : DataItem, StringOutputItem {
// Some subclass methods
}
class IntItem : DataItem, IntOutputItem {
// Some subclass methods
}
となることによって:
let item1 = StringItem()
print(item1.rawValue()) // should give "string output"
let item2 = AnotherStringItem()
print(item2.rawValue()) // should give "string output"
let item3 = IntItem()
print(item3.rawValue()) // should give 123
デフォルトの実装を提供するためにプロトコル拡張がどのように機能するかについて、私が完全にベースから外れている場合、私は同じ結果を達成する方法についてオープンなアイデアを持っています。