Remove specific object from array in swift 3

2020-02-23 07:15发布

问题:

I have a problem trying to remove a specific object from an array in Swift 3. I want to remove item from an array as in the screenshot but I don't know the solution.

If you have any solutions please share with me.

回答1:

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



回答2:

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.



回答3:

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]"


标签: arrays swift3