我有两个这样的数组:
var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
如您所见,James
和Steve
匹配,我希望能够将其从arrayA
中删除。我怎么写这个?
答案 0 :(得分:47)
@ francesco-vadicamo的回答 Swift 2/3/4 +
arrayA = arrayA.filter { !arrayB.contains($0) }
答案 1 :(得分:29)
最简单的方法是使用新的Set
容器(在Swift 1.2 / Xcode 6.3中添加):
var setA = Set(arrayA)
var setB = Set(arrayB)
// Return a set with all values contained in both A and B
let intersection = setA.intersect(setB)
// Return a set with all values in A which are not contained in B
let diff = setA.subtract(setB)
如果要将结果集重新分配给arrayA
,只需使用复制构造函数创建一个新实例并将其分配给arrayA
:
arrayA = Array(intersection)
缺点是您必须创建2个新数据集。
请注意,intersect
不会改变它所调用的实例,它只返回一个新集。
有类似的方法可以添加,减去等,你可以看看它们
答案 2 :(得分:18)
像这样:
var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
for word in arrayB {
if let ix = find(arrayA, word) {
arrayA.removeAtIndex(ix)
}
}
// now arrayA is ["Mike", "Stacey"]
答案 3 :(得分:13)
我同意Antonio的回答,但是对于小数组减法,你也可以使用这样的过滤器闭包:
let res = arrayA.filter { !contains(arrayB, $0) }
答案 4 :(得分:10)
matt和freytag的解决方案是唯一能够解决重复问题的解决方案,并且应该比其他答案获得更多的+1。
以下是对于Swift 3.0的matt的答案的更新版本:
var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
for word in arrayB {
if let ix = arrayA.index(of: word) {
arrayA.remove(at: ix)
}
}
答案 5 :(得分:5)
这也可以实现为减号:
u'2016\u5e741\u67081\u65e5'
现在你可以使用
func -<T:RangeReplaceableCollectionType where T.Generator.Element:Equatable>( lhs:T, rhs:T ) -> T {
var lhs = lhs
for element in rhs {
if let index = lhs.indexOf(element) { lhs.removeAtIndex(index) }
}
return lhs
}
答案 6 :(得分:4)
使用安东尼奥提到的Array → Set → Array
方法,并且操作员的方便,正如弗雷塔格所指出的那样,我对此非常满意:
// Swift 3.x/4.x
func - <Element: Hashable>(lhs: [Element], rhs: [Element]) -> [Element]
{
return Array(Set<Element>(lhs).subtracting(Set<Element>(rhs)))
}
答案 7 :(得分:1)
使用索引数组删除元素:
字符串和索引数组
let animals = ["cats", "dogs", "chimps", "moose", "squarrel", "cow"]
let indexAnimals = [0, 3, 4]
let arrayRemainingAnimals = animals
.enumerated()
.filter { !indexAnimals.contains($0.offset) }
.map { $0.element }
print(arrayRemainingAnimals)
//result - ["dogs", "chimps", "cow"]
整数和索引数组
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
let indexesToRemove = [3, 5, 8, 12]
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains($0.offset) }
.map { $0.element }
print(numbers)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
使用其他数组的元素值删除元素
整数数组
let arrayResult = numbers.filter { element in
return !indexesToRemove.contains(element)
}
print(arrayResult)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
字符串数组
let arrayLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
let arrayRemoveLetters = ["a", "e", "g", "h"]
let arrayRemainingLetters = arrayLetters.filter {
!arrayRemoveLetters.contains($0)
}
print(arrayRemainingLetters)
//result - ["b", "c", "d", "f", "i"]
答案 8 :(得分:0)
对于较小的数组,我使用:
let date = new Date();