I'm struggling to understand protocols and protocol extensions in swift.
I'm wanting to define a series of protocols that can be applied to a class, along with a set of protocol extensions to provide default implementations. Example code:
// 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
}
}
The above override functions for rawValue()
in the extensions give an error Ambiguous type name 'ResultType' in 'Self'
. If I remove Self
, from Self.ResultType
, I get the error 'ResultType' is ambiguous for type lookup in this context
.
How do I signal to the protocol extension which type to use for ResultType
?
My aim is to be able to apply the protocols and their extensions to a class as follows:
// 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
}
So that:
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
If I'm completely off base with how protocol extensions work to provide default implementations, I'm open ideas of how to achieve the same outcome.