【发布时间】:2026-01-27 18:40:02
【问题描述】:
假设我有这个简单的通用协议
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,我的字符串文字就是这样做的。那么为什么没有约束就不行呢?
谢谢!
【问题讨论】:
标签: swift generics constraints protocols