【发布时间】:2020-08-10 08:34:03
【问题描述】:
我想创建一个函数来选择哪个实现好,像这样:
// As a BaseProtocol
protocol BaseProtocol {
}
// SeniorProtocol with associatedtype
protocol SeniorProtocol {
associatedtype S
}
// First implementation of SeniorProtocol
struct SeniorImpl1:SeniorProtocol {
typealias S = BaseProtocol
init() {}
}
// Second implementation of SeniorProtocol
struct SeniorImpl2:SeniorProtocol {
typealias S = BaseProtocol
init() {}
}
// The function
func whichImpl<T: SeniorProtocol>() -> T{
if Int.random(in: 0 ... 5) < 3 {
return SeniorImpl1() as! T
}
else {
return SeniorImpl2() as! T
}
}
最后,当我跑步时
var c = whichImpl()
我收到此错误:“无法推断通用参数 'T'”。 似乎编译器不知道 T 是什么。 我该如何解决?我只想做whichImpl()中写的代码
【问题讨论】:
-
你想要达到什么目的?您对泛型的使用完全有缺陷,因为您返回的不是泛型类型,而是具体类型,因此会出现编译器错误。
-
我只想返回一个符合协议“SeniorProtocol”条件的结构。因为'SeniorProtocol'有关联类型,所以不能是返回值。
-
你必须做标准 Swift 库所做的事情:创建
AnySenior(类似于AnyCollection) 类型擦除的包装器,然后返回它。 -
我担心这是不可能的(我不确定这是否是个好主意)。 user28434 的解决方案可能是一个不错的解决方案。使用
some关键字也不是一个选项:docs.swift.org/swift-book/LanguageGuide/OpaqueTypes.html#ID614。这个问题也可能有帮助:stackoverflow.com/questions/40034034/…。我认为如果您向我们提供更多背景信息将是最好的,这样我们就可以查看是否有更适合您的情况的解决方案。