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
Answer from Martin R on Stack Overflow
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!)"}))
🌐
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!

🌐
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 ...
🌐
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. You can easily support sarunw.com by checking out this sponsor. AI Paraphrase:Are you tired of staring at your screen, struggling to rephrase sentences, or trying to find the perfect words for your text?
🌐
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 ...
🌐
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.
🌐
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.
🌐
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...
Find elsewhere
Top answer
1 of 3
16

So I quickly did this to help out, if someone can improve that's fine I'm just trying to help.

I made a struct for the books

struct Book {
    let title: String
    let tag: [String]
}

Created an array of those

var books: [Book] = []

Which is empty.

I created a new object for each book and appended to books

let dv = Book(title: "The Da Vinci Code", tag: ["Religion","Mystery", "Europe"])
books.append(dv)
let gdt = Book(title: "The Girl With the Dragon Tatoo", tag: ["Psychology","Mystery", "Thriller"])
books.append(gdt)
let fn = Book(title: "Freakonomics", tag: ["Economics","non-fiction", "Psychology"])
books.append(fn)

So you've three objects in the books array now. Try to check with

print (books.count)

Now you want to filter for Psychology books. I filtered the array for tags of Psychology - are filters ok for you?

let filtered = books.filter{ $0.tag.contains("Psychology") } 
filtered.forEach { print($0) }

Which prints the objects with your two Psychology books

Book(title: "The Girl With the Dragon Tatoo", tag: ["Psychology", "Mystery", "Thriller"])

Book(title: "Freakonomics", tag: ["Economics", "non-fiction", "Psychology"])

2 of 3
1

Representing the books as an array of tuples with named parameters title and tags for book title and tags respectively.

let books:[(title:String, tags:String)] = [

    (title: "The Da Vinci Code", tags: "Religion, Mystery, Europe"),
    (title: "The Girl With the Dragon Tatoo", tags: "Psychology, Mystery, Thriller"),
    (title: "Freakonomics", tags: "Economics, non-fiction, Psychology")

]

You want to search for tag Psychology

let searchedTag = "Psychology"

We can use filter function to filter out the items in the books array that only contains the tag we are looking for.

let searchedBooks = books.filter{ $0.tags.split(separator: ",").map{ return $0.trimmingCharacters(in: .whitespaces) }.contains( searchedTag ) }

print(searchedBooks)

Inside the filter method, we have created an array of tag items from book tags using split(separator: Character) method. Next, using map function, we remove the leading and trailing whitespaces from each tag. Finally, using .contains(element) method, we test if the tag we are looking for is in this array. Only the tuples passing this test are returned and the others will be filtered out.

The result is:

[(title: "The Girl With the Dragon Tatoo", tags: "Psychology, Mystery, Thriller"), (title: "Freakonomics", tags: "Economics, non-fiction, Psychology")]

🌐
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.
🌐
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 · Set: An unordered collection of values (where all the values are of the same type)
🌐
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.
🌐
Apple Developer
developer.apple.com › forums › thread › 70148
Swift 3 filter array by date | Apple Developer Forums
December 29, 2016 - The underscore for the parameter name is telling the closure to ignore the argument (each element of an array in this case) passed to it. Try it with a parameter named `item`: let filteredItems = items.filter { item in return item.completeDate == date } ... See the Swift Programming Language ebook (also in Xcode documentation) for info about closure syntax.
🌐
Cocoa Casts
cocoacasts.com › swift-fundamentals-how-to-find-an-object-in-an-array
How to Find an Object in an Array
The filter(_:) method accepts a closure as its only argument. The closure accepts an object of type Int and its return value is Bool. The resulting array includes every object of the array for which the closure returns true. Like many other programming languages, Swift includes a wide range ...
🌐
Apple Developer
developer.apple.com › forums › thread › 693772
filter an object array based on an… | Apple Developer Forums
How can you judge if an Option exist in the selected Array? Compare userCode? Compare optType? Compare optValue? Or some other way? ... extension Selected { func matches(_ option: Option) -> Bool { //↓Modify the following expression to fit for your purpose return optType == option.optType && optValue == option.optValue } } ... Button("Options Not Selected") { let optionsNotSelected = options.filter { option in !selected.contains {$0.matches(option)} } print(optionsNotSelected) //Use `optionsNotSelected`... }
🌐
Hacking with Swift
hackingwithswift.com › books › ios-swiftui › dynamically-filtering-a-swiftui-list
Dynamically filtering a SwiftUI List - a free Hacking with iOS: SwiftUI Edition tutorial
January 3, 2022 - The easiest way to do this is using Swift’s filter() method. This runs every element in a sequence through a test you provide as a closure, and any elements that return true from the test are sent back as part of a new array.