Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific object from array in swift 3

Tags:

Remove Object From Array Swift 3

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.

like image 770
Socheat Avatar asked Dec 21 '16 05:12

Socheat


People also ask

How to remove particular item from Array in Swift?

Swift Array remove() The remove() method removes an element from the array at the specified index.


1 Answers

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

like image 175
Mohammadalijf Avatar answered Sep 28 '22 17:09

Mohammadalijf