Swift 2.0检查多维数组是否包含特定数组

时间:2015-10-03 20:23:53

标签: arrays swift2

我有一组正确的组合,如下面的

[["dbc", "dbs", "dbt"], ["dyc", "dys", "dyt"], ["drc", "drs", "drt"]]

并希望在我的组合

时查看我的组合是否包含任何正确的组合
[["drs", "gbc", "lrs"], ["grt", "lbc", "lbt"], ["drc", "drs", "drt"], ["dyc", "dys", "dyt"]]

如果有任何匹配,则打印出正确的组合。

我已经测试了.contains,但我想它只适用于在一维数组中找到一个元素。如何检查多维数组是否包含特定数组?

2 个答案:

答案 0 :(得分:2)

因此,换句话说,你有2个元素列表(其中一个元素是一个包含3个字符串的数组),你想要找到2个列表中的交集

access-control-

希望这有帮助

P.S。我的回答的逻辑类似于 egor.zhdan 所描述的逻辑。我只是使用Swift本机let corrects : Set = [["dbc", "dbs", "dbt"], ["dyc", "dys", "dyt"], ["drc", "drs", "drt"]] let all : Set = [["drs", "gbc", "lrs"], ["grt", "lbc", "lbt"], ["drc", "drs", "drt"], ["dyc", "dys", "dyt"]] let intersection = Array(corrects.intersect(all)) intersection // [["dyc", "dys", "dyt"], ["drc", "drs", "drt"]] 结构而不是从Objective-C桥接的Set / NSSet类。

答案 1 :(得分:0)

您可以使用NSMutableSetintersectSet方法执行此操作:

let correct = [["dbc", "dbs", "dbt"], ["dyc", "dys", "dyt"], ["drc", "drs", "drt"]]
let all = [["drs", "gbc", "lrs"], ["grt", "lbc", "lbt"], ["drc", "drs", "drt"], ["dyc", "dys", "dyt"]]

let correctSet = NSSet(array: correct)
let allSet = NSMutableSet(array: all)
allSet.intersectSet(correctSet as Set<NSObject>)

print(allSet) // prints (("drc", "drs", "drt"), ("dyc", "dys", "dyt"))