- 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 }
- }
如果您首先不关心模型一致性,则可以使用标准库的AnyHashable
类型擦除包装器来完全任意Hashable一致性实例.
但是,假设您关心模型一致性,则必须为符合Model和Hashable的实例构建自己的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属性并从AnyHashableModel本身中删除Model一致性,使调用者访问基础Model符合实例的基础:
- struct AnyHashableModel : Hashable {
- // ...
- let base: Model
- // ...
- }
但是,您会注意到上述类型擦除的包装器仅适用于Hashable和Model的类型.如果我们想谈论符合实例Hashable的其他协议怎么办?
正如我演示in this Q&A,更通用的解决方案是接受Hashable并且符合其他协议的类型 – 其类型由通用占位符表示.
因为Swift目前还没有办法表达一个通用占位符,它必须符合另一个通用占位符给出的协议;必须由调用者使用转换闭包来定义此关系,以执行必要的向上转换.但是,由于Swift 3.1接受扩展中的具体相同类型要求,我们可以定义一个方便初始化器来删除Model的样板(这可以在其他协议类型中重复).
例如:
- /// 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)