Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Array remove only one item with a specific value

Tags:

arrays

swift3

Alright, this should not be too difficult, but Sunday morning proves me wrong...

I have an Array with structs, and want to remove only one struct that matches its name property to a String. For example:

struct Person {
   let name: String
}

var myPersons =
[Person(name: "Jim"),
 Person(name: "Bob"),
 Person(name: "Julie"),
 Person(name: "Bob")]

func removePersonsWith(name: String) {
   myPersons = myPersons.filter { $0.name != name }
}

removePersonsWith(name: "Bob")
print(myPersons)

results in:

[Person(name: "Jim"), Person(name: "Julie")]

But how do I only remove one Bob?

like image 599
koen Avatar asked Jan 23 '26 14:01

koen


1 Answers

  • filter filters all items which match the condition.

  • firstIndex returns the index of the first item which matches the condition.

      func removePersonsWith(name: String) {
          if let index = myPersons.firstIndex(where: {$0.name == name}) {
              myPersons.remove(at: index)
          }
      }
    

However the name of the function is misleading. It's supposed to be removeAPersonWith ;-)

like image 160
vadian Avatar answered Jan 25 '26 11:01

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!