如何检查通用class中协议的关联类型的具体类型?
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
例如我有一个协议和一些 类 符合它:
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