检查Hashable一致性

时间:2017-04-06 18:41:39

标签: swift generics

我有一个基本协议(模型),一些结构符合。它们也符合Hashable

protocol Model {}
struct Contact: Model, Hashable {
    var hashValue: Int { return ... }
    static func ==(lhs: Contact, rhs: Contact) -> Bool { return ... } 
}
struct Address: Model, Hashable {
    var hashValue: Int { return ... }
    static func ==(lhs: Address, rhs: Address) -> Bool { return ... } 
}

我有一个函数,它接受一个符合Model([Model])的对象数组。 如何将[Model]传递给需要Hashables而不使Model Hashable的函数?

func complete(with models: [Model]) {
    doSomethingWithHashable(models) //can't do this
}
func doSomethingWithHashable <T:Hashable>(_ objects: [T]) {
    //
}

我试图避免这个

protocol Model: Hashable {}
func complete<T:Model>(with models: [T]) {
    runComparison(models)
}

因为当我这样做时,我得到“模型不能用作通用约束......”

protocol SomethingElse {
    var data: [Model] { get }
}

1 个答案:

答案 0 :(得分:2)

您的代码存在的问题是您正在谈论Model,它承诺没有关于Hashable一致性。正如您所指出的那样,告诉编译器有关此问题(即从Model派生Hashable)的问题是您失去了根据符合Model的异构类型进行交谈的能力。

如果您一开始并不关心Model一致性,那么您可以使用标准库的AnyHashable类型擦除包装完全随意 Hashable符合实例。

但是,假设您确实关注Model一致性,那么您必须为符合ModelHashable的实例构建自己的type-erased wrapper。在my answer here中,我演示了如何为Equatable符合类型构建类型橡皮擦。那里的逻辑可以很容易地扩展到Hashable - 我们只需要存储一个额外的函数来返回实例的hashValue

例如:

struct AnyHashableModel : Model, Hashable {

    static func ==(lhs: AnyHashableModel, rhs: AnyHashableModel) -> Bool {

        // forward to both lhs's and rhs's _isEqual in order to determine equality.
        // the reason that both must be called is to preserve symmetry for when a
        // superclass is being compared with a subclass.
        // if you know you're always working with value types, you can omit one of them.
        return lhs._isEqual(rhs) || rhs._isEqual(lhs)
    }

    private let base: Model

    private let _isEqual: (_ to: AnyHashableModel) -> Bool
    private let _hashValue: () -> Int

    init<T : Model>(_ base: T) where T : Hashable {

        self.base = base

        _isEqual = {
            // attempt to cast the passed instance to the concrete type that
            // AnyHashableModel was initialised with, returning the result of that
            // type's == implementation, or false otherwise.
            if let other = $0.base as? T {
                return base == other
            } else {
                return false
            }
        }

        // simply assign a closure that captures base and returns its hashValue
        _hashValue = { base.hashValue }
    }

    var hashValue: Int { return _hashValue() }
}

然后你会这样使用它:

func complete(with models: [AnyHashableModel]) {
    doSomethingWithHashable(models)
}

func doSomethingWithHashable<T : Hashable>(_ objects: [T]) {
    //
}

let models = [AnyHashableModel(Contact()), AnyHashableModel(Address())]
complete(with: models)

我假设您还希望将其用作Model要求的包装(假设有一些要求)。或者,您可以公开base属性并从Model本身中删除AnyHashableModel一致性,使调用者访问基础base符合实例的Model:< / p>

struct AnyHashableModel : Hashable {
    // ...
    let base: Model
    // ...
}

但请注意,上述类型删除的包装器仅适用于HashableModel的类型。如果我们想谈谈符合实例Hashable的其他协议怎么办?

我演示in this Q&A时,更通用的解决方案是接受同时属于Hashable并符合其他协议的类型 - 其类型由通用占位符表示。

因为目前Swift没有办法表达一个通用的占位符,它必须符合另一个通用占位符给出的协议;此关系必须由具有transform闭包的调用者定义,以执行必要的upcast。但是,由于Swift 3.1在扩展中接受了具体的相同类型要求,我们可以定义一个便捷初始化器来删除Model的这个样板(这可以在其他协议类型中重复)。 / p>

例如:

/// Type-erased wrapper for a type that conforms to Hashable,
/// but inherits from/conforms to a type T that doesn't necessarily require
/// Hashable conformance. In almost all cases, T should be a protocol type.
struct AnySpecificHashable<T> : Hashable {

    static func ==(lhs: AnySpecificHashable, rhs: AnySpecificHashable) -> Bool {
        return lhs._isEqual(rhs) || rhs._isEqual(lhs)
    }

    let base: T

    private let _isEqual: (_ to: AnySpecificHashable) -> Bool
    private let _hashValue: () -> Int

    init<U : Hashable>(_ base: U, upcast: (U) -> T) {

        self.base = upcast(base)

        _isEqual = {
            if let other = $0.base as? U {
                return base == other
            } else {
                return false
            }
        }

        _hashValue = { base.hashValue }
    }
    var hashValue: Int { return _hashValue() }
}

// extension for convenience initialiser for when T is Model.
extension AnySpecificHashable where T == Model {
    init<U : Model>(_ base: U) where U : Hashable {
        self.init(base, upcast: { $0 })
    }
}

您现在想要将实例包装在AnySpecificHashable<Model>

func complete(with models: [AnySpecificHashable<Model>]) {
    doSomethingWithHashable(models)
}

func doSomethingWithHashable<T : Hashable>(_ objects: [T]) {
    //
}

let models: [AnySpecificHashable<Model>] = [
    AnySpecificHashable(Contact()),
    AnySpecificHashable(Address())
]

complete(with: models)