3

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?

4
  • tell me what differentiates between the two Bobs, then I'll tell you how. But if not, you can set a bool flag so once the filter is set to false it would exit the loop Commented Dec 4, 2016 at 16:05
  • The two Bobs are exactly the same, they are clones of each other, but I only want to remove one of them. Commented Dec 4, 2016 at 16:06
  • I'm just curious that why are you up to such functionality? Is it to remove duplicates? Or something else? Commented Dec 4, 2016 at 16:13
  • Person is just an example. I could have used a different example, eg balls with different colors, and then remove one red ball. Or fish in a river, and catch (remove) one salmon, etc. Commented Dec 4, 2016 at 16:18

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

I don't think this is what the OP eventually wants. He wants to erase all but one ie if he has 5 Bobs, he would want to remove 4 of them, this on removes 1 of them. Koen, please let us know what you want. Otherwise good answer
No, I only want to remove one Bob
In terms of naming, I would call the method removeFirstPersonWith(name: String) to make it a little more clear.
@AllanSpreys I mentioned the ambiguity in the answer.
Yes, I know :) I’m recommending an alternative to those who find the answer helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.