例如,我有一个协议和一些符合该协议的类:
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'(aka'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