比较两个不同数组中的值

时间:2015-11-09 14:22:00

标签: arrays compare swift2

我试图比较Swift中两个数组的值。如果在array2中找不到array1的值,则需要列出并删除所有array2找到的值。

我试图使用下面的代码,但它在Swift 2中不再起作用了:

let array1 = [["aaa","12"],["bbb","349"],["ccc","91"],["ddd","143"]]
let array2 = ["aaa","SSS","bbb","ccc","QQQ","ZZZ","ddd"]

let notNeededValues = filter(enumerate(zip(array1,array2))) { $1.0 == $1.1 }.map{ $0.0 }

print(notNeededValues)

2 个答案:

答案 0 :(得分:1)

不确定我是否正确理解您的问题,但问题似乎是,您的代码需要简单转换为Swift 2语法:

let array1 = [["aaa","12"],["bbb","349"],["ccc","91"],["ddd","143"]]
let array2 = ["aaa","SSS","bbb","ccc","QQQ","ZZZ","ddd"]

let notNeededValues = zip(array1, array2).enumerate().filter { $1.0 == $1.1 }.map { $0.0 }

print(notNeededValues)

Swift正在逐渐摆脱全局定义的函数,例如filterenumerate,而是使用点语法。协议扩展使这一变化成为可能,并使代码更具可读性。

<强>更新

我认为这就是你的意思(?):

let notNeededValues = array2.filter { !array1.map { $0[0] }.contains($0) }

// or like this:
let array1FirstElements = array1.map { $0[0] }
let notNeededValues = array2.filter { !array1FirstElements.contains($0) }

答案 1 :(得分:0)

这个怎么样:

let array1 = [["aaa","12"],["bbb","349"],["ccc","91"],["ddd","143"]]
let array2 = ["aaa","SSS","bbb","ccc","QQQ","ZZZ","ddd"]

extension Array where Element: Equatable {
    func removeObject(object: Element) -> [Element] {
        return filter {$0 != object}
    }
}

var filteredArray2 = array2.reduce(array2) {
    if array1.flatMap({$0}).contains($1) {
        return $0.removeObject($1)
    }
    return $0
}

print(filteredArray2)