Reputation: 65
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
Upvotes: 2
Views: 75
Reputation: 171
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 }
Upvotes: 0
Reputation: 236305
You can use RangeReplaceableCollection
mutating method:
mutating func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows
In your case:
strNames.removeAll { $0.id == 4 }
Upvotes: 4