Remove specific object from array in swift 3

后端 未结 3 403
无人及你
无人及你 2020-12-29 05:43

\"Remove

I have a problem trying to remove a specific object from an array in Swift

相关标签:
3条回答
  • 2020-12-29 06:02

    Short Answer

    you can find the index of object in array then remove it with index.

    var array = [1, 2, 3, 4, 5, 6, 7]
    var itemToRemove = 4
    if let index = array.index(of: itemToRemove) {
        array.remove(at: index)
    }
    

    Long Answer

    if your array elements confirm to Hashable protocol you can use

    array.index(of: itemToRemove)
    

    because Swift can find the index by checking hashValue of array elements.

    but if your elements doesn't confirm to Hashable protocol or you don't want find index base on hashValue then you should tell index method how to find the item. so you use index(where: ) instead which asks you to give a predicate clouser to find right element

    // just a struct which doesn't confirm to Hashable
    struct Item {
        let value: Int
    }
    
    // item that needs to be removed from array
    let itemToRemove = Item(value: 4)
    
    // finding index using index(where:) method
    if let index = array.index(where: { $0.value == itemToRemove.value }) {
    
        // removing item
        array.remove(at: index)
    }
    

    if you are using index(where:) method in lots of places you can define a predicate function and pass it to index(where:)

    // predicate function for items
    func itemPredicate(item: Item) -> Bool {
        return item.value == itemToRemove.value
    }
    
    if let index = array.index(where: itemPredicate) {
        array.remove(at: index)
    }
    

    for more info please read Apple's developer documents:

    index(where:)

    index(of:)

    0 讨论(0)
  • 2020-12-29 06:08

    According to your code, the improvement could be like this:

        if let index = arrPickerData.index(where: { $0.tag == pickerViewTag }) {
            arrPickerData.remove(at: index)
            //continue do: arrPickerData.append(...)
        }
    

    The index existing means Array contains the object with that Tag.

    0 讨论(0)
  • 2020-12-29 06:29

    I used the solutions provided here: Remove Specific Array Element, Equal to String - Swift Ask Question

    this is one of the solutions there (in case the object was a string):

    myArrayOfStrings = ["Hello","Playground","World"]
    myArrayOfStrings = myArrayOfStrings.filter{$0 != "Hello"}
    print(myArrayOfStrings)   // "[Playground, World]"
    
    0 讨论(0)
提交回复
热议问题