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

I want to remove single object from multiple matching object like

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

When I remove

myArray.removeObject(2) 

then both objects are deleted. I want remove only single object.

I tried to use many extension but no one is working properly. I have already used this link.

Community
  • 1
  • 1
ikbal
  • 1,114
  • 1
  • 11
  • 30

3 Answers3

7

Swift 2

Solution when using a simple Swift array:

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

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

It works because .indexOf only returns the first occurence of the found object, as an Optional (it will be nil if object not found).

It works a bit differently if you're using 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 will return Int.max when failing to find an object at this index, so we check for this specific error before removing the object.

Swift 3

The syntax has changed but the idea is the same.

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]

In Swift 3 we call index(of:) on both Array and NSMutableArray, but they still behave differently for different collection types, like indexOf and indexOfObject did in Swift 2.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • Eric, i am using mutable array in my project so, generate this type of error, Value of type 'NSMutableArray' has no member 'indexOf' – ikbal Jan 25 '16 at 11:23
0

Swift 5: getting index of the first occurrence

if let i = yourArray.firstIndex(of: yourObject) {
   yourArray.remove(at: i)
}
-1

If you want to remove all duplicate objects then you can use below code.

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

    let set = NSSet(array: testarray as [AnyObject])
    print(set.allObjects)
kb920
  • 3,039
  • 2
  • 33
  • 44