I am having a strange issue while implementing Swift generic protocol.
Please refer to this playground code snippet.
import Foundation
protocol FooProtocol {
static func foo() -> String
}
struct Outer<T: FooProtocol>: FooProtocol {
static func foo() -> String {
return T.foo()
}
}
struct Inner<T>: FooProtocol {
static func foo() -> String {
return "default. T is \(T.self)"
}
}
extension Inner where T == String {
static func foo() -> String {
return "Inner String"
}
}
extension Inner where T == Int {
static func foo() -> String {
return "Inner Int"
}
}
print(Inner<Int>.foo())
print(Outer<Inner<Int>>.foo())
print(Inner<String>.foo())
print(Outer<Inner<String>>.foo())
The result of this is
Inner Int
default. T is Int
Inner String
default. T is String
The result I expected is:
Inner Int
Inner Int
Inner String
Inner String
What bothers me is that Inner
struct totally works. It runs into default implementation when it is contained in Outer
struct. Can anyone explain this?
Also, is there a way to achieve what I am trying to do here?