根据对象标识

时间:2017-10-10 07:50:18

标签: swift collections duplicates

我正在编写用于缓存类实例的组件。这些课程本身不是ComparableHashableEquatable。如果是这样的话,各个操作的语义不一定符合我们的目的,所以我们不能使用这些协议。

对象可以缓存w.r.t.多个键。因此,当向缓存请求所有缓存对象的列表时,我需要从基础字典的值集中删除重复项 - 与对象标识相关。

显然,这可以胜任:

var result: [C] = []
for c in dict.values {
    if !result.contains(where: { (rc: C) in rc === c }) {
        result.append(c)
    }
}
return result

但是,这具有二次运行时行为。与使用上述协议(使用集合实现)时容易获得的线性或预期线性行为相比,这很糟糕。

那么我们如何才能有效地删除重复项w.r.t. Swift集合中的对象标识?

1 个答案:

答案 0 :(得分:0)

我们可以将对象包装成 var tag = decodeURIComponent(location.search.split('tag=')[1]); Hashable

Comparable

现在,任何常规的struct ClassWrap<T: AnyObject>: Hashable, Comparable { var value: T var hashValue: Int { return ObjectIdentifier(self.value).hashValue } static func ==(lhs: ClassWrap, rhs: ClassWrap) -> Bool { return lhs.value === rhs.value } static func <(lhs: ClassWrap<T>, rhs: ClassWrap<T>) -> Bool { return ObjectIdentifier(lhs.value) < ObjectIdentifier(rhs.value) } } 实施或其他独特的操作应该可以胜任。