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

3
我定义了两种类型,如下所示:我想定义一个名为“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
    }

}

我该如何比较结构体的“类型”?这一直是个头痛的问题。我应该使用AnyObject吗?

2个回答

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

2
您需要的工具是object_getClassName(返回一个String)。目前,您无法直接比较类型。这感觉只是一个缺失的编译器特性,而不是Swift的任何深层问题。您可能会认为可以比较x.dynamicType == y.dynamicType,但目前不起作用。另请参见实体和Equatable的模式是什么?

1
你只能对对象使用 object_getClassName 方法。如果它们都是对象,你可以使用 x.dynamicType as AnyObject === y.dynamicType as AnyObject - newacct

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接