【发布时间】:2020-03-15 19:02:28
【问题描述】:
我正在尝试实现一个具有泛型参数的协议方法,然后在我的整个类中使用泛型类型,而不是仅仅在方法上使用,就像这样
protocol FirstProtocol {
}
protocol SecondProtocol {
func foo<T: FirstProtocol>(argument: T)
}
class MyType<T: FirstProtocol>: SecondProtocol {
var value: T? = nil
func foo<T>(argument: T) {
value = argument // ERROR: Cannot assign value of type 'T' to type 'T?'
}
}
所以 swift 编译器接受 foo<T>(argument:T) 匹配 SecondProtocol 的方法,如果我注释掉错误行它编译得很好,但它不会让我将 argument 分配给 value 即使 value 和 argument 应该是相同的类型,编译器也会抱怨它们是不同的类型。
【问题讨论】:
-
我试过
value = T?.some(argument),它给了我Cannot assign value of type 'Optional<T>' to type 'T?'错误。
标签: swift generics swift-protocols swift5