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
🌐
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 - extension Array { func partiallyContains(check: Element) -> Bool where Element == String { for str in self { if str.contains(check) { return true } } return false } func partiallyContainsFilter(word: Element) -> [Element] where Element == String { self.filter({$0.contains(word)}) } }var array = ["hello","world","hello world"]array.contains("he") // falsearray.partiallyContains(check: "he") // truearray.partiallyContainsFilter(word: "he") // ["hello", "hello world"]
🌐
Sarunw
sarunw.com › posts › swift-array-filter
How to Filter an Array in Swift | Sarunw
July 10, 2023 - In summary, to filter an array, you pass a closure telling which element you want to keep in the final array. Return true, if you want to keep it. Return false to discard. ... Different ways to sort an array of strings in Swift 26 Dec 2020 Read more article about Swift, Array, or see all available topic
🌐
Programiz
programiz.com › swift-programming › library › array › filter
Swift Array filter() (With Examples)
String Methods View all · Python · JavaScript · C · C++ Java · R · Kotlin · Become a certified Python programmer. Try Programiz PRO! Add two numbers · Check prime number · Find the factorial of a number · Print the Fibonacci sequence · Check leap year All Python Examples · Swift Array append() Swift Array contains() Swift Array dropFirst() Swift Array dropLast() Swift Array insert() Swift Array joined() Swift Array min() Swift Array remove() Swift Array removeAll() Swift Array removeSubrange() Swift Array reverse() Swift Array sort() Swift Array swapAt() Swift Array allSatisfy() Sw
🌐
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!

🌐
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...
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)", [:])
Find elsewhere
🌐
Sarunw
sarunw.com › posts › swift-array-contains
How to check if an Element is in an Array in Swift | Sarunw
December 21, 2022 - Swift Array has two methods to check whether an element is in an array. ... The contains(_:) method returns true if an array contains the given element. This method only supports an array in which Element conforms to the Equatable protocol.
🌐
Stack Overflow
stackoverflow.com › questions › 53471531 › how-to-filter-an-array-containing-a-string-and-an-array-of-structure-objects-in
swift - How to filter an array containing a string and an array of structure objects, in which there is a string parameter? - Stack Overflow
I have an array var friendsListGroupedFiltered = [Object]() of this structure struct Object { var letters : String var sectionObjects : [Friend] } that contains an array of objects of a...
🌐
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.
🌐
Donny Wals
donnywals.com › how-to-filter-an-array-in-swift
How to filter an Array in Swift? – Donny Wals
April 23, 2024 - Instead, filter(isIncluded:) creates a new Array with only the elements you want. You can perform any kind of calculation, comparison or computation in the closure that you use, just keep in mind that the more work you in your closure, the slower ...
🌐
Programiz
programiz.com › swift-programming › library › array › contains
Swift Array contains() (With Examples)
The contains() method checks whether the specified element is present in the array or not. The contains() method checks whether the specified element is present in the array or not. Example var languages = ["Swift", "C", "Java"] // check if languages contains "Swift" var result = ...
🌐
DhiWise
dhiwise.com › post › efficient-data-refinement-with-swift-array-filter-strategies
Mastering Swift Array Filter: A Comprehensive Guide
September 10, 2024 - In the code snippet above, the names array is initialized with a set of names, and the filter function is used to create a new array shortNames containing only the names with fewer than 5 characters. By specifying the condition { $0.count < 5 } within the filter closure, the initial value for filtering is set to include only names that satisfy the character length criterion. Setting an appropriate initial value for filtering arrays in Swift enables you to focus the filter function on specific elements that meet the defined criteria, resulting in a refined output that aligns with the desired outcome.
🌐
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.