如何比较两个"通用"数组中迅速 [英] How to compare two "generic" array in swift

查看:111
本文介绍了如何比较两个"通用"数组中迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

var tstFrames = [TimeFrame]()
var tstFramesRefresh = [TimeFrame]()

是否有人知道如何将它们进行比较?

Does anybody know how to compare them?

我发现了一些实例添加数组设置,但设置没有初始化,可以接受此数组类型..:(

I found some examples adding array to Set, but Set doesn't have initializer which can accept this arraytype.. :(

两个阵列具有几乎时限对象的同一实例,但tstFramesRefresh具有一个更这是不是在tstFrames阵列我会得到一个时间框架对象。

The two array has almost the same instances of TimeFrame object but tstFramesRefresh has one more which is not in tstFrames array i would get that one TimeFrame object.

推荐答案

当你说比较 - 你的意思是平等的,字典比较或差异?听起来像是你想有一个差异。

When you say "compare" – do you mean equal, lexicographic comparison, or diff? Sounds like you want a diff.

该组解决方案可能是这样的(假设你想在没有其他的一个东西,而不是脱节二):

The set solution might look like this (assuming you want things in one not in the other, rather than the disjunction of the two):

let a = [1,2,3]
let b = [1,2]

Set(a).subtract(b)  // returns a set of {3}

presumably您的问题是,时间表哈希,因此它不会里面工作集。

Presumably your issue is that TimeFrame is not Hashable, hence it won’t work inside a set.

你也可以使用包含来检查,如果每个元素 A 为成员。不幸的是这将是大型成套相当低效的,因为包含工作于线性时间,所以复杂度将为O(n ^ 2)。但它很容易做到:

You could instead use contains to check if each element of a were a member of b. Unfortunately this will be quite inefficient for large sets, since contains works in linear time so complexity will be O(n^2). But it’s easy to do:

func subtract<S: SequenceType, C: CollectionType, T: Equatable
    where C.Generator.Element == T, S.Generator.Element == T>
    (source: S, toSubtract: C) -> [S.Generator.Element] {
        return filter(source) { !contains(toSubtract, $0) }
}


subtract(a, b)  // returns [3]

更有效的解决方案,如果你的对象是可比可以使用排序或树结构。

More efficient solutions if your object were Comparable could use sorting or a tree structure.

如果你的对象不是 Equatable 要么,你需要一个带一个封闭检查等价版本:

If your objects aren’t Equatable either, you’d need a version that took a closure to check for equivalence:

func subtract<S: SequenceType, C: CollectionType>
    (source: S, toSubtract: C,
     isEquivalent: (S.Generator.Element, C.Generator.Element) -> Bool)
    -> [S.Generator.Element] {
        let x = filter(source) { elem in
            return !contains(toSubtract) { isEquivalent(elem,$0) }
        }
        return x
}

subtract(a, b) { $0 == $1 }

如果你只是要检查它们是否相等,那么 == 将做到这一点 - 除非对象不equatable,在这种情况下使用,它接受一个比较函数等于功能:

If you just want to check if they are equal, then == will do it – unless the objects aren’t equatable, in which case use the equal function that takes a comparator function:

// asuming these are classes and reference equality is reasonable thing to check
equal(tstFrames, tstFramesRefresh) { $0 === $1 } 

这篇关于如何比较两个&QUOT;通用&QUOT;数组中迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆