如何从多个匹配对象中删除数组中的单个对象

2023-12-06

var testarray = NSArray() 
testarray = [1,2,2,3,4,5,3] 
print(testarray) 
testarray.removeObject(2)

我想从多个匹配对象中删除单个对象,例如

myArray = [1,2,2,3,4,3]

当我删除时

myArray.removeObject(2) 

然后两个对象都被删除。我只想删除单个对象。

我尝试使用许多扩展,但没有一个可以正常工作。我已经用过这个链接.


Swift 2

使用简单 Swift 数组时的解决方案:

var myArray = [1, 2, 2, 3, 4, 3]

if let index = myArray.indexOf(2) {
    myArray.removeAtIndex(index)
}

它有效是因为.indexOf只返回第一次出现找到的对象,作为可选(它将是nil如果未找到对象)。

如果您使用 NSMutableArray,它的工作方式会有点不同:

let nsarr = NSMutableArray(array: [1, 2, 2, 3, 4, 3])
let index = nsarr.indexOfObject(2)
if index < Int.max {
    nsarr.removeObjectAtIndex(index)
}

Here .indexOfObject将返回Int.max当无法在此索引处找到对象时,因此我们在删除对象之前检查此特定错误。

Swift 3

语法已经改变,但思想是一样的。

Array:

var myArray = [1, 2, 2, 3, 4, 3]
if let index = myArray.index(of: 2) {
    myArray.remove(at: index)
}
myArray // [1, 2, 3, 4, 3]

NSMutableArray:

let myArray = NSMutableArray(array: [1, 2, 2, 3, 4, 3])
let index = myArray.index(of: 2)
if index < Int.max {
    myArray.removeObject(at: index)
}
myArray // [1, 2, 3, 4, 3]

在 Swift 3 中我们称之为index(of:)在 Array 和 NSMutableArray 上,但对于不同的集合类型,它们的行为仍然不同,例如indexOf and indexOfObject在 Swift 2 中做到了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从多个匹配对象中删除数组中的单个对象 的相关文章

随机推荐