gpt4 book ai didi

ios - 过滤两个数组 Swift

转载 作者:可可西里 更新时间:2023-10-31 23:53:09 25 4
gpt4 key购买 nike

我有一个空数组和两个有数据的数组

var resultsArray = [String]()

var array1 = ["1","2","2","3","4"]
var array2 = ["1","2","2","3","4","5","6"]

我的目标是在 resultsArray 中附加 array2 中不匹配 array1 的元素(“5”和“6”在示例中)。

这样做最巧妙的方法是什么?

谢谢。

最佳答案

使用 filter功能

var resultsArray = [String]()

let array1 = ["1","2","2","3","4"]
let array2 = ["1","2","2","3","4","5","6"]

let filteredArray = array2.filter{ !array1.contains($0) }

resultsArray.appendContentsOf(filteredArray)

如果集合包含独特的项目,请考虑使用 Set而不是 Array


更新 Swift 5.1:

在 iOS 13、macOS 10.15 中有一个新的 API Array

public func difference<C>(from other: C) -> CollectionDifference<Element> where C : BidirectionalCollection, Self.Element == C.Element


var resultsArray = [String]()

let array1 = ["1","2","2","3","4"]
let array2 = ["1","2","2","3","4","5","6"]

let diff = array2.difference(from: array1)
resultsArray.append(contentsOf: array1)
for change in diff {
switch change {
case .remove(let offset, _, _): resultsArray.remove(at: offset)
case .insert(let offset, let element, _): resultsArray.insert(element, at: offset)
}
}

关于ios - 过滤两个数组 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35680135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com