Ohefoof
Ohefoof

Reputation: 1

Delete strings from array that do not contain substring

I want to delete the strings from an array that do not contain the substring "originals". I tried this and it didn't work, it just printed the whole array. I need like the equivalent of a for i loop from Java.

for (position, imageURL) in imageURLs.enumerated() {
    if !imageURLs[position].contains("originals"){
        imageURLs.remove(at: position)
    }
}
print(imageURLs)

Upvotes: 0

Views: 53

Answers (1)

Ranoiaetep
Ranoiaetep

Reputation: 6647

Removing elements from a sequence while iterating through the sequence is often bug-prone. Consider removing from the collection directly with a predicate:

imageURLs.removeAll{ !$0.contains("originals") }

Upvotes: 1

Related Questions