How to remove element from array from instance member?

Having placed instances of a class into an array of another class I would like to remove the entire instance but because they all have the same name I cannot, but I would like to use a member called name.

var mammals: Creatures = Creatures(alive: true, safe: [sanctuary], injured: [hospital])

sanctuary: [Animals] = [goat, lion, parrot]

let goat = Animals(name: "Terry", age: 13, legs: 4)
let lion = Animals(name: "Benjamin", age: 5, legs: 4)
let parrot = Animals(name: "Berty", age: 2, legs: 2)

When I check the sanctuary array through the mammals class member the elements displays with only their class name e.g. [Animals, Animals, Animals]. How do remove an element, I have tried using the where function from removeAll(where:) but it will not accept any of the instance members?

I suppose I am not doing it right?

What I found to work was to replicate what I had done with the sanctuary array and add the elements as variables themselves so that each instance of the class would be given an appropriate name.

However, to find the specific element I found the where clause in the remove function to be a workable solution:

mammals.safe.removeAll(where: { $0.age > 10} )

I'm not sure what is meant here by remove the entire instance, because they all have the same name I cannot, and I would like to use a member called name.

Judging by the predicate removeAll(where:) is the option, but as the name says it will remove all elements that satisfy the predicate. If the first match is the one you're after, you should rather loop through the array until you find the relevant element.

Hi anthonylatsis, that's right, I contain the where clause in a loop and do just that.

It works.

Thanks.

Terms of Service

Privacy Policy

Cookie Policy