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.
Swift Array remove() The remove() method removes an element from the array at the specified index.
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:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With