swift - 我可以比较 Any.Type 吗?

Ryn*_*eow 3 ios swift

我定义了两种类型,如下:我想定义一个函数“matches”,它比较两个 KeyTypePairs 并根据键和类型的匹配返回 true 或 false。

protocol KeyTypePair: Hashable {
    typealias val

    var key: String { get }
    var type: Any.Type { get }
}

public struct KeyTypePairOf<T>: KeyTypePair {
    typealias val = T

    let _key: String
    let _type: Any.Type

    public var key: String {
        get {
            return _key
        }
    }

    public var type: Any.Type {
        get {
            return _type
        }
    }

    public var hashValue: Int {
        get {
            return _key.hashValue
        }
    }

    public init(key: String) {
        self._key = key
        self._type = T.self
    }

    init<T: KeyTypePair>(property: T) {
        self._key = pair.key
        self._type = pair.type
    }

    func matches<T: KeyTypePair>(pair:T) -> Bool {
        let x = self._type == pair.type // invalid, how do I check equal types?
        return self._key == pair.key && x
    }

}
Run Code Online (Sandbox Code Playgroud)

如何比较结构的“类型”?一直很头疼。我应该使用 AnyObject 吗?

小智 5

我在 Swift 4 Playground 中测试了这个

struct Foo {}
struct Bar {}

let fooType: Any.Type = Foo.self
let barType: Any.Type = Bar.self

fooType == Foo.self  // true
fooType is Foo.Type  // true
fooType == barType   // false
Run Code Online (Sandbox Code Playgroud)