【问题标题】:How to check the concrete type of associatedtype of a protocol inside generic class?如何检查泛型类中协议的关联类型的具体类型?
【发布时间】:2020-05-23 15:53:21
【问题描述】:

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

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

【问题讨论】:

    标签: swift swift5 swift-protocols


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多