Removing object from array in Swift 3

前端 未结 13 2076
余生分开走
余生分开走 2020-12-08 12:49

In my application I added one object in array when select cell and unselect and remove object when re-select cell. I used that code but give me error.

extens         


        
13条回答
  •  一整个雨季
    2020-12-08 13:11

    The Swift equivalent to NSMutableArray's removeObject is:

    var array = ["alpha", "beta", "gamma"]
    
    if let index = array.firstIndex(of: "beta") {
        array.remove(at: index)
    }
    

    if the objects are unique. There is no need at all to cast to NSArray and use indexOfObject:

    The API index(of: also works but this causes an unnecessary implicit bridge cast to NSArray.

    If there are multiple occurrences of the same object use filter. However in cases like data source arrays where an index is associated with a particular object firstIndex(of is preferable because it's faster than filter.

    Update:

    In Swift 4.2+ you can remove one or multiple occurrences of beta with removeAll(where:):

    array.removeAll{$0 == "beta"}
    

提交回复
热议问题