0
我有一个通用协议,它有一个返回通用参数的方法。协议有两种实现方式,都将字符串作为返回类型。我想要一种方法来构建一个类似于基于某个参数的类集群的特定实例。该方法限制了泛型类型,但有试图返回时的错误:返回专用类型的通用协议swift的方法
“不能类型StringReturn返回表达式转换成返回类型T”
protocol GenericProtocol {
typealias ReturnType
func doSomething() -> ReturnType
}
struct StringReturn : GenericProtocol {
func doSomething() -> String {
return "first"
}
}
struct AnotherStringReturn : GenericProtocol {
func doSomething() -> String {
return "another"
}
}
func build<T : GenericProtocol where T.ReturnType == String>(param: String) -> T {
if .. {
return StringReturn()
} else {
return AnotherStringReturn
}
}
嗨,这很好,但我想要的功能来决定什么T结束了,这可能吗? –
@LukeDeFeo如果你想基于某些条件返回一个对象,我想你可以使用'GenericProtocol'的常规函数作为返回类型。问题是你的协议有一个相关的类型'ReturnType',它不可能用它作为返回类型。 –
是的,所以我不会能够返回通用协议,因为它具有自我要求,它只能用作通用约束。很烦人,我发现通用协议几乎是无用的:/ –