在实施Swift通用协议时遇到一个奇怪的问题。请参阅此游乐场代码段。
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())
此结果是
Inner Int
default. T is Int
Inner String
default. T is String
[困扰我的是Inner
结构完全有效。当它包含在Outer
结构中时,它将运行到默认实现中。谁能解释一下?另外,有没有办法实现我在这里想要做的事情?
Outer<Inner<Int>>.foo()
根据Inner<Int>
结构的foo()
方法调用Outer
的静态foo()
方法:
struct Outer<T: FooProtocol>: FooProtocol {
static func foo() -> String {
return T.foo() // Here T is Inner<Int>. So its foo() is called returning "default. T is Int"
}
}
在上面的代码段中,T为Inner<Int>
。因此,它的foo()
被称为返回“ default。T is Int”。