Search code examples
arraysswift3

Swift Array remove only one item with a specific value


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?


Solution

    • 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 ;-)