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 中做到了。