How to remove single object in array from multiple matching object

后端 未结 2 656
一整个雨季
一整个雨季 2021-01-22 14:05
var testarray = NSArray() 
testarray = [1,2,2,3,4,5,3] 
print(testarray) 
testarray.removeObject(2)

I want to remove single object from multiple matchi

相关标签:
2条回答
  • 2021-01-22 14:52

    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.

    0 讨论(0)
  • 2021-01-22 14:56

    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)
    
    0 讨论(0)
提交回复
热议问题