【发布时间】:2020-02-26 20:37:29
【问题描述】:
我目前正在 Swift 中使用泛型进行试验,但在将某些类型(例如 SomeType<Protocol> 转换为 SomeType<ProtocolImpl>)时遇到了一些问题。所以基本上我有一些类型,它接受一个作为协议处理的泛型参数,稍后将其转换为更具体的类型。我的问题是,如果这不可能吗?
/// 'dict' is of type [String: SomeType<Protocol>]
if let element = dict["str"], // 'element' here is of type SomeType<Protocol>
let castedElement = element as? SomeType<ProtocolImpl> { // This is always false
return castedElement // Here I want to return castedElement with type SomeType<ProtocolImpl>
}
有什么办法可以让这个演员工作?我已经在为我的问题寻找另一种解决方案,但我仍然对是否有办法以某种方式完成这项工作感兴趣。
编辑:因为@jtbandes 想要一个可以粘贴到某处的示例,所以在这里:
class SomeType<T> {
let value: T
init(value: T) {
self.value = value
}
}
protocol Protocol {}
class ProtocolImpl: Protocol {}
var dict: [String: SomeType<Protocol>] = ["str": SomeType(value: ProtocolImpl())]
if let element = dict["str"],
let castedElement = element as? SomeType<ProtocolImpl> {
print(castedElement.value) // I want to get here
}
【问题讨论】:
-
您编写它的方式是不可能的,但如果您edit 您的问题包括minimal reproducible example,那么也许有人可以就不同的解决方案为您提供建议。
-
您不能将
dict[String:type]转换为type。它是一个包含您的类型实例的字典,但它不是您的类型的实例,无论您如何抽象。 -
@Putz1103 代码中没有任何地方从字典转换为其他类型,请再次仔细阅读。
dict["str"]的类型为SomeType<Protocol> -
为什么不检查
let castedElement = element.value as? ProtocolImpl。这应该可以正常工作。 -
@Putz1103 虽然这可以编译,但这不是我的目标。我想要从数组中引用 SomeType
对象,而不是 ProtocolImpl 对象。