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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Eric, i am using mutable array in my project so, generate this type of error, Value of type 'NSMutableArray' has no member 'indexOf'
0

Swift 5: getting index of the first occurrence

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

Comments

-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)

4 Comments

Off-topic. OP said I want to remove single object.
"I want to remove single object from multiple matching object like" value 3 is also 2 times!
You don't understand. :) OP doesn't asks to remove duplicate objects. He asks to remove only one of the duplicates.
Then question should be how to remove object from index 2 from array [1,2,2,3,4,5,3]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.