Use contains instead:

let arr = ["Hello","Bye","Halo"]
let filtered = arr.filter { $0.contains("lo") }
print(filtered)

Output

["Hello", "Halo"]

Thanks to @user3441734 for pointing out that functionality is of course only available when you import Foundation

Answer from luk2302 on Stack Overflow
🌐
Swift Forums
forums.swift.org › using swift
Filter array with another array - Using Swift - Swift Forums
June 29, 2022 - I would like to create a new array of strings that dont contain strings from another array. I have it working in the long form. But would like to learn a more Swift way of doing it The return filteredList would be ["music", "unicorns rainbow walkers"] let removelist : [String] = ["nerf", "magic beans"] let originalList : [String] = ["nerf", "music", "unicorns rainbow walkers", "magic beans"] // tried this but not exactly working //let filtered = originalList.filter { $0.contains(where: { rem...
🌐
Sarunw
sarunw.com › posts › swift-array-filter
How to Filter an Array in Swift | Sarunw
July 10, 2023 - AI Paraphrase:Are you tired of staring at your screen, struggling to rephrase sentences, or trying to find the perfect words for your text? ... Swift Array has an instance method, filter(_:), that removes unwanted elements from the resulting array.
🌐
Programiz
programiz.com › swift-programming › library › array › filter
Swift Array filter() (With Examples)
Swift String removeAll() The filter() method returns all the elements from the array that satisfy the provided condition. var numbers = [2, 3, 6, 9] // return all the elements greater than 5 var result = numbers.filter({ $0 > 5}) print(result) // Output: [6, 9] The syntax of the filter() method ...
🌐
Apple Developer
developer.apple.com › documentation › swift › string › filter(_:)
filter(_:) | Apple Developer Documentation
Returns a new collection of the same type containing, in order, the elements of the original collection that satisfy the given predicate.
🌐
Donny Wals
donnywals.com › how-to-filter-an-array-in-swift
How to filter an Array in Swift? – Donny Wals
April 23, 2024 - Let's say you have an array of ... "world", "this", "list", "strings"] The filter(isIncluded:) method takes a closure that is executed for every element in the source Array....
Top answer
1 of 4
16

[Updated for Swift 2.0]

As NSString is toll-free bridged to Swift String, just avoid the coercions with:

  3> ["abc", "bcd", "xyz"].filter() { nil != $0.rangeOfString("bc") }
$R1: [String] = 2 values {
  [0] = "abc"
  [1] = "bcd"
}

But, if you think allValues aren't strings:

(keywords.allValues as? [String]).filter() { nil != $0.rangeOfString("bc") }

which returns an optional array.

2 of 4
4

Your filter is over [AnyObject], but your closure takes NSString. These need to match. Also, your result needs to be a Bool, not a Bool?. You can address these simply like this:

self.filteredKeywords = filter(keywords.allValues, {
    let keyword = $0 as? NSString
    return keyword?.containsString(searchText) ?? false
})

This accepts AnyObject and then tries to coerce it down to NSString. It then nil-coalleces (??) the result to make sure it always is a Bool.

I'd recommend, though, treating keywords as a [String:String] rather than an NSDictionary. That would get rid of all the complications of AnyObject. Then you can just do this:

self.filteredKeywords = keywords.values.filter { $0.rangeOfString(searchText) != nil }

Whenever possible, convert Foundation collections into Swift collections as soon as you can and store those. If you have incoming Foundation objects, you can generally convert them easily with techniques like:

let dict = nsdict as? [String:String] ?? [:]

Or you can do the following to convert them such that they'll crash in debug (but silently "work" in release):

func failWith<T>(msg: String, value: T) -> T {
    assertionFailure(msg)
    return value
}

let dict = nsdict as? [String:String] ?? failWith("Couldn't convert \(d)", [:])
🌐
Reddit
reddit.com › r/swift › filtering array of objects by strings in another array.
r/swift on Reddit: Filtering array of objects by strings in another array.
October 30, 2015 -

I have an array of Match objects [Match] with a string property of matchID. I also have an array of strings.

I would like to remove the Match object where matchID equals any string in the array.

I currently have:

                var matches = [Match]
                var matchIDsToDelete = [String]

                for match in matches {
                    for id in matchIDsToDelete {
                        if match.matchID == id {
                            // remove that item from array
                        }
                    }
                }

My concern is removing the object from the array as I'm enumerating. I believe there will be consequences. Any suggestions? I would also love a functional solution as I'm currently reading more about functional programming.

Thanks!

Find elsewhere
🌐
Hacking with Swift
hackingwithswift.com › example-code › language › how-to-remove-items-from-an-array-using-filter
How to remove items from an array using filter() - free Swift example code and tips
May 28, 2019 - The filter() method goes over all the items in an array (or indeed any kind of collection), and returns a new array containing items that pass a test you specify. ... NEW You don’t need more Swift tutorials.
🌐
Brightec
brightec.co.uk › home › blog › how to filter, map, and reduce in swift
Swift Basics: Mapping, Filtering, and Reducing in Swift |… | Brightec
August 16, 2023 - If you want to remove duplicates, the easiest option may be to wrap it in a set Set(articles.flatMap(\.tags)). Filtering is as you'd expect - take an array and filter/remove items from it, returning another array of the same type.
🌐
Medium
medium.com › nerd-for-tech › make-swift-contains-and-filter-ready-for-ios-development-e60a6570f5a2
Make swift ‘contains()’ and ‘filter()’ ready for iOS Development | by Sai Durga Mahesh | Nerd For Tech | Medium
May 26, 2021 - But finally as we aimed at starting of article we need to add much more flexibility for array to use in case of “searching in contacts”. extension Array { func flexibleElementsEqual(with array: [Element]) -> Bool where Element == String { var result = true for i in array { if !self.partiallyContains(check: i) { result = false return result } } return result } func flexibleFilter(word: Element) -> [Element] where Element == String { let arrayToBeChecked = word.components(separatedBy: " ") return self.filter { i in let wordtobechecked = i.components(separatedBy: " ") return wordtobechecked.flexibleElementsEqual(with: arrayToBeChecked) } }}var array = ["hello","world","hello world"]array.flexibleFilter(word: "wo") // ["world", "hello world"]array.flexibleFilter(word: "rld") // ["world", "hello world"]
🌐
Apple Developer
developer.apple.com › forums › thread › 669894
Filter array by String | Apple Developer Forums
In your way of creating groupedArray, its keys contains section titles. ["A", "B", ...] If you want to filter rows by name, you need to move filter to the second ForEach: You may want to remove empty sections, but that needs a little more complex code. ... Is groupedArray a dictionary ?
🌐
Hacking with Swift
hackingwithswift.com › read › 39 › 6 › filtering-using-functions-as-parameters
Filtering using functions as parameters - a free Hacking with Swift tutorial
May 28, 2019 - We're going to add the ability for users to filter the word list in one of two ways: by showing only words that occur at or greater than a certain frequency, or by showing words that contain a specific string. This will work by giving PlayData a new array, filteredWords, that will store all words that matches the user's filter.
🌐
TutorialKart
tutorialkart.com › swift-tutorial › swift-array-filter
How to Filter a Swift Array based on a Condition?
May 2, 2021 - Swift – Check if Specific Key is present in Dictionary ... To filter elements of a Swift Array, call filter() method on this array and pass the predicate/condition to the filter() method.
🌐
Stack Overflow
stackoverflow.com › questions › 32699884 › swift-array-filtering
ios - Swift Array Filtering - Stack Overflow
I have a Game Class with property id: String and im trying to filter the array gamesArray: [Game] based on ids contained in another array haveGameArray: [String] and return the results on gamesFilteredArray: [Game] // Filter the array by the contained in self.haveGameArray self.gamesFilteredArray = self.gamesArray.filter( { (game: Game) -> Bool in let id = game.id return self.haveGameArray.contains(id) }) Its not working and i don't know what to do, because the logic its right ... If you are looking for a simple perfect example of Array filter in Swift2, this is it.