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

标签 ios swift

我定义了两种类型如下:我想定义一个函数“匹配”来比较两个 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 吗?

最佳答案

我在 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

关于ios - swift - 我可以比较 Any.Type 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25992233/

相关文章:

ios - swift 中类似 Tinder 的导航

ios - iOS 应用中的定向广告

cocoa - Swift 中的 SCNScene 问题 : nothing shows in SCNView

ios - 在 SwiftUI 中暂停通知发布者

ios - 是否建议在 iOS 应用程序中手动删除手势识别器

ios - 它显示 "required initializer init must be provided in subclass of UIControl"当我覆盖 init(frame : CGRect)

ios - MapBox:如何删除一个形状并绘制另一个形状?

ios - Swift 中的 Google 登录问题

ios - 即使队列中有项目,skipPrevious 和 skipNext 按钮也无效 Google Cast iOS Sender SDK v4.3.5 及更高版本

xcode - Swift 代码改进