D'Andre Ealy D'Andre Ealy - 2 months ago 13
Swift Question

How to iterate through Array and remove an item based off a string value

I have a string with is a prefix. I'm iterating over an Array of String and if the value contains the prefix then I want to remove that item from the

Array
. My code is giving me the error:


fatal error: Index out of range.


I need some direction on how to handle something like this.

for (index, value) in arrayValues.enumerated() {
if value.contains(prefixValue) {
arrayValues.remove(at: index)
}
}

Answer

Have you try to use filter for that.

var filterArray = arrayValues.filter { !$0.contains(prefixValue) }

For case insensitive Swift 3

var filterArray = arrayValues.filter { !$0.lowercased().contains(prefixValue) }

For case insensitive Swift 2.3 or lower

var filterArray = arrayValues.filter { !$0.lowercaseString.contains(prefixValue) }