2

I have a custom array like this and I want to delete the element where Student id is 4

var strNames = [Student(id: 1, name: "ghj"), Student(id: 4, name: "def"), Student(id: 9, name: "bkl")]

In classic way I do like this. Can anybody please help me mapping in Swift way?

 var sArray2: [Student] = []
    for item in strNames {
        if item.id != 4 {
            sArray2.append(Student(id: item.id, name: item.name))
        }
    }
strNames = sArray2

2 Answers 2

4

You can use RangeReplaceableCollection mutating method:

mutating func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows

In your case:

strNames.removeAll { $0.id == 4 }
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use filter function to filter out based on a condition, but filter function returns a new array with the filtered values

var filteredArray = strNames.filter { (eachVal) -> Bool in eachVal.id != 4 }

Comments

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.