比较2个数组并列出差异 - Swift

sim*_*sd3 11 arrays boolean compare swift

我想知道如何比较2个布尔数组并列出不匹配的布尔值.

我写了一个2个数组的简单例子.

let array1 = [true, false, true, false]
let array2 = [true, true, true, true]
Run Code Online (Sandbox Code Playgroud)

我如何比较array1和array2并显示不匹配.我试图这样做来检查测验游戏的用户结果.

谢谢!

mat*_*att 30

这是一个实现,但是它是否是你所追求的是完全不可能说,因为你没有指定你认为答案应该是:

let answer = zip(array1, array2).map {$0.0 == $0.1}
Run Code Online (Sandbox Code Playgroud)

true如果答案与正确答案匹配,那么会为您提供Bool值列表,如果答案不匹配false.

但是,让我们说你想要的是那些正确答案的索引列表.然后你可以说:

let answer = zip(array1, array2).enumerated().filter() {
    $1.0 == $1.1
}.map{$0.0}
Run Code Online (Sandbox Code Playgroud)

如果您想要那些正确的答案的索引列表,只需更改==!=.

  • 真正伟大的是,这个答案设法将`map`,`filter`,`zip`和`enumerate`放在一起 - 为了在Swift中使用数组你需要了解的关键事项(仅限) `reduce`被忽略了 - 在这个问题中无法找到它的用途).:) (7认同)

Ji *_*ang 10

支持 Xcode 11(仅适用于 iOS 13 或更新版本)

https://developer.apple.com/documentation/swift/array/3200716-difference

let oldNames = ["a", "b", "c", "d"]
    
let newNames = ["a", "b", "d", "e"]

let difference = newNames.difference(from: oldNames)

for change in difference {
  switch change {
  case let .remove(offset, oldElement, _):
    print("remove:", offset, oldElement)
  case let .insert(offset, newElement, _):
    print("insert:", offset, newElement)
  }
}
Run Code Online (Sandbox Code Playgroud)

输出

remove: 2 c
insert: 3 e
Run Code Online (Sandbox Code Playgroud)

  • 尝试使用差异时出现此错误。**“difference(from:)”仅在 iOS 13 或更高版本中可用** (4认同)

Rav*_*ati 6

最简单的方法是使用Set。集合具有一个恰好可以做到这一点的symmetricDifference()方法,因此您只需要将两个数组都转换为一个集合,然后将结果转换回一个数组即可。

这是使它变得更容易的扩展:

extension Array where Element: Hashable {
    func difference(from other: [Element]) -> [Element] {
        let thisSet = Set(self)
        let otherSet = Set(other)
        return Array(thisSet.symmetricDifference(otherSet))
    } }
Run Code Online (Sandbox Code Playgroud)

这是一些示例代码,您可以用来尝试:

let names1 = ["student", "class", "teacher"]
let names2 = ["class", "Teacher", "classroom"]
let difference = names1.difference(from: names2)
Run Code Online (Sandbox Code Playgroud)

这会将差异设置为[“ student”,“ classroom”],因为这是在两个数组中仅出现一次的两个名称。

  • [来源](https://www.hackingwithswift.com/example-code/language/how-to-find-the-difference-between-two-arrays) (7认同)
  • @DoesData我正要发表同样的评论,然后我意识到这个答案是在 hackingwithswift 帖子之前发布的,所以也许_this_是_他们的_来源。 (4认同)
  • @monstermac77 很公平。但是,该链接仍然提供了更多详细信息并且很有帮助。[Apple文档](https://developer.apple.com/documentation/swift/set/3128856-symmetrydifference)也提供了一个具体的示例。 (2认同)