假设我有这个简单的通用协议
protocol FooProtocol {
associatedtype Element: CustomStringConvertible
func echo(element: Element) -> Element
}
和实现它的这个简单的通用结构
struct FooStruct<Element: CustomStringConvertible>: FooProtocol {
func echo(element: Element) -> Element {
return element
}
}
最后,我具有以下功能:
func callEcho<T: FooProtocol>(container: T) {
container.echo(element: "some string")
}
这导致 error: cannot invoke 'echo' with an argument list of type '(element: String)'
解决方案是将功能更改为
func callEcho<T: FooProtocol>(container: T) where T.Element == String {
container.echo(element: "some string")
}
我的问题是:为什么where T.Element == String
约束是必要的?编译器知道这T
是一个实现的实体FooProtocol
,而协议仅要求Element
实现CustomStringConvertible
,这是我的字符串文字所做的。那么,为什么没有约束就行不通呢?
谢谢!
我不确定为什么要说“该协议只要求Element实现CustomStringConvertible”。该协议要求echo
接受并返回其Element,该Element可以是String,也可以不是。例如,我可以实现以下符合类型:
struct AnotherFoo: FooProtocol {
func echo(element: Int) -> Int { fatalError() }
}
因此,如果我随后致电:
callEcho(container: AnotherFoo())
这将尝试将字符串文字传递给需要Int的函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句