如何检查泛型类内部协议的关联类型的具体类型?

问题描述 投票:0回答:1

例如,我有一个协议和一些符合该协议的类:

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永远不会成功。

swift swift5 swift-protocols
1个回答
1
投票

仅按照警告建议将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
© www.soinside.com 2019 - 2024. All rights reserved.