One approach is to update your filter to see if any value in pets is in the petArr array:

users = users.filter { $0.pets.contains(where: { petArr.contains($0) }) }

The first $0 is from the filter and it represents each User.

The second $0 is from the first contains and it represents each pet within the pets array of the current User.

Answer from rmaddy on Stack Overflow
🌐
Apple Developer
developer.apple.com › documentation › swift › array › filter(_:)
filter(_:) | Apple Developer Documentation
Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
🌐
Programiz
programiz.com › swift-programming › library › array › filter
Swift Array filter() (With Examples)
The filter() method returns all the elements from the array that satisfy the provided condition. The filter() method returns all the elements from the array that satisfy the provided condition. Example var numbers = [2, 3, 6, 9] // return all the elements greater than 5 var result = ...
🌐
Sarunw
sarunw.com › posts › swift-array-filter
How to Filter an Array in Swift | Sarunw
July 10, 2023 - let names = ["Alice", "Bob", "John"] let shortNames = names.filter { name in if name.count < 4 { // 1 ... 1 We return true for an element we want to keep. In this case, we want to keep a name shorter than four characters, name.count < 4. 2 For other names, we return false to discard them. The resulting array contains only names shorter than four characters which is only **"Bob"**in this case.
🌐
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.
🌐
Donny Wals
donnywals.com › how-to-filter-an-array-in-swift
How to filter an Array in Swift? – Donny Wals
April 23, 2024 - When you have an Array of elements, and you want to drop all elements that don't match specific criteria from the Array, you're looking for Array's filter(isIncluded:) method.
🌐
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...
🌐
Codecademy
codecademy.com › docs › swift › arrays › .filter()
Swift | Arrays | .filter() | Codecademy
June 28, 2023 - The .filter() method takes an array and returns a new array with only elements that meet the condition stated in the filter. If none of the elements meet the condition stated in the filter, the method returns nil.
Find elsewhere
🌐
Medium
medium.com › swlh › filtering-in-swift-8524bbd55119
Filtering in Swift. Filtering is an extremely important… | by Steven Curtis | The Startup | Medium
February 20, 2022 - Filter: Acts on a collection type and returns an Array where the elements that are returned match the condition given in the Array
🌐
TutorialKart
tutorialkart.com › swift-tutorial › swift-array-filter
How to Filter a Swift Array based on a Condition?
May 2, 2021 - To filter elements of a Swift Array, call filter() method on this array and pass the predicate/condition to the filter() method.
Top answer
1 of 7
51

contains() checks if a sequence contains a given element, e.g. if a String contains a given Character.

If your intention is to find all books where the name contains the substring "rt", then you can use rangeOfString():

var arr = englishBooks.filter {
    $0.nameOfBook.rangeOfString("rt") != nil
}

or for case-insensitive comparison:

var arr = englishBooks.filter {
    $0.nameOfBook.rangeOfString("rt", options: .CaseInsensitiveSearch) != nil
}

As of Swift 2, you can use

nameOfBook.containsString("rt") // or
nameOfBook.localizedCaseInsensitiveContainsString("rt")

and in Swift 3 this is

nameOfBook.contains("rt") // or
nameOfBook.localizedStandardContains("rt") // or
nameOfBook.range(of: "rt", options: .caseInsensitive) != nil
2 of 7
17

Sorry this is an old thread. Change you code slightly to properly init your variable 'nameOfBook'.

class book{
   var nameOfBook: String!
   init(name: String) {
      nameOfBook = name
   }
}

Then we can create an array of books.

var englishBooks = [book(name: "Big Nose"), book(name: "English Future 
Prime Minister"), book(name: "Phenomenon")]

The array's 'filter' function takes one argument and some logics, 'contains' function can take a simplest form of a string you are searching for.

let list1 = englishBooks.filter { (name) -> Bool in
   name.contains("English")
}

You can then print out list1 like so:

let list2 = arr1.map({ (book) -> String in
   return book.nameOfBook
})
print(list2)

// print ["English Future Prime Minister"]

Above two snippets can be written short hand like so:

let list3 = englishBooks.filter{ ($0.nameOfBook.contains("English")) }
print(list3.map({"\($0.nameOfBook!)"}))
🌐
DhiWise
dhiwise.com › post › efficient-data-refinement-with-swift-array-filter-strategies
Mastering Swift Array Filter: A Comprehensive Guide
September 10, 2024 - In the world of Swift development, manipulating arrays efficiently is a common task. One fundamental operation when working with arrays is filtering - the process of selecting only the elements that meet specific criteria.
🌐
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.
🌐
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"]
Top answer
1 of 3
4
struct Address {
    var name: String
    var imageURL: String
    var address: String
}

let VIPArray = [["name": "John B"], ["name": "Sara K"]]

let AddressArray = [Address(name: "John B",  imageURL: "johnb", address: "178 Main St."),
                    Address(name: "Dave H",  imageURL: "daveh", address: "1011 Victoria St.."),
                    Address(name: "Sara K",  imageURL: "sarak", address: "279 Maple Av."),
                    Address(name: "Niles K", imageURL: "nilesk", address: "45 King St."),
                    Address(name: "Ingrid G",  imageURL: "ingridg", address: "33 Union St.")]


var filtered = [Address]()

for element in VIPArray {
    for address in AddressArray {
        if element["name"] == address.name {
            filtered.append(address)
        }
    }
}

for record in filtered {
    print(record)
}

OUTPUT:

Address(name: "John B", imageURL: "johnb", address: "178 Main St.")

Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av.")

Or:

let filtered: [Address] = AddressArray.filter { (address) -> Bool in
    for vip in VIPArray {
        if vip["name"] == address.name {
            return true
        }
    }
    return false
}
2 of 3
4
let VIPArray = [["name": "John B"], ["name": "Sara K"]]

struct Address {
    let name: String
    let imageURL: String
    let address: String
}

let addressArray = [Address(name: "John B",  imageURL: "johnb", address: "178 Main St."),
                    Address(name: "Dave H",  imageURL: "daveh", address: "1011 Victoria St.."),
                    Address(name: "Sara K",  imageURL: "sarak", address: "279 Maple Av."),
                    Address(name: "Niles K", imageURL: "nilesk", address: "45 King St."),
                    Address(name: "Ingrid G",  imageURL: "ingridg", address: "33 Union St.")]

let myVips = addressArray.filter() {VIPArray.contains(["name":$0.name])}
🌐
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 - Using map, filter, and reduce in Swift results in clean, concise code that is more readable and offers better results. This supports us in our endeavour to develop high-performance apps with a people-first approach. Mapping is the process of converting an array from 1 type to another [A] to [B]. There are lots of reasons to do this, a simple example is extracting an array of user IDs from an array of users.
🌐
Bugfender
bugfender.com › blog › swift-arrays
Swift Arrays: Map, Filter, Reduce & Sort Explained | Bugfender
November 7, 2025 - Swift arrays are value-type data structures that copy on write, ensuring predictable behavior and thread safety. We should use sort() or sorted() to organize data, and choose filter() to extract only the elements we need.