![](/img/trans.png)
[英]Protocol inheritance from a generic class using associatedType as Type
[英]How to check the concrete type of associatedtype of a protocol inside generic class?
例如,我有一个协议和一些符合它的类:
protocol SomeProtocol {
associatedtype SomeType: Encodable
}
class SomeInner: SomeProtocol {
typealias SomeType = String
}
class SomeInner2: SomeProtocol {
typealias SomeType = URL
}
class AnotherClass<Inner: SomeProtocol> {
func someFunc() {
if Inner.SomeType.self is String { // << warning
print("it's a String")
}
if Inner.SomeType.self is URL { // << warning
print("it's an URL")
}
}
}
let test1 = AnotherClass<SomeInner>()
test1.someFunc()
let test2 = AnotherClass<SomeInner2>()
test2.someFunc()
这给了我警告:
从“Inner.SomeType.Type”(又名“String.Type”)转换为不相关类型“String”总是失败
从“Inner.SomeType.Type”转换为不相关类型“URL”总是失败
if
永远不会成功。
只需按照警告的建议将String
更改为String.Type
:
func someFunc() {
if Inner.SomeType.self is String.Type { // << warning
print("it's a String")
}
if Inner.SomeType.self is URL.Type { // << warning
print("it's an URL")
}
}
它编译并输出
it's a String
it's an URL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.