我正在努力快速理解协议和协议扩展。
我想定义一系列可应用于类的协议,以及一组协议扩展以提供默认实现。示例代码:
// 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
如果我完全不了解协议扩展如何提供默认实现,那么我对如何实现相同结果持开放态度。