Forget about the filter for a moment. Think how you would check if a car's color is a value in an array.

let colors = [ "Green", "Blue" ]
// or let colors: Set = [ "Green", "Blue" ]
if colors.contains(someCar.color) {
}

Simple enough. Now use that same simple expression in the filter.

let filterdObject = cars.filter { $0.model == currModel || colors.contains($0.color) }
Answer from rmaddy on Stack Overflow
๐ŸŒ
Programiz
programiz.com โ€บ swift-programming โ€บ library โ€บ array โ€บ filter
Swift Array filter() (With Examples)
// return all the elements that start with "N" var result = languages.filter( { $0.hasPrefix("N") } ) print(result) ... This is a short-hand closure that checks whether all the elements in the array have the prefix "N" or not. $0 is the shortcut to mean the first parameter passed into the closure. The closure returns a Bool value depending upon the condition.
People also ask

Can you filter an array in Swift?
Yes, you can filter an array in Swift using the filter function to selectively extract elements that meet specific criteria.
๐ŸŒ
dhiwise.com
dhiwise.com โ€บ post โ€บ efficient-data-refinement-with-swift-array-filter-strategies
Mastering Swift Array Filter: A Comprehensive Guide
How do you apply a filter on an array of objects in Swift?
To filter an array of objects in Swift, you can define a filtering condition using a closure that checks specific properties of the objects and then use the filter function to create a new array with the filtered elements.
๐ŸŒ
dhiwise.com
dhiwise.com โ€บ post โ€บ efficient-data-refinement-with-swift-array-filter-strategies
Mastering Swift Array Filter: A Comprehensive Guide
How does the filter() function work in Swift?
The filter() function in Swift evaluates each element of an array based on a given condition and returns a new array containing only the elements that satisfy that condition.
๐ŸŒ
dhiwise.com
dhiwise.com โ€บ post โ€บ efficient-data-refinement-with-swift-array-filter-strategies
Mastering Swift Array Filter: A Comprehensive Guide
๐ŸŒ
Iswift
iswift.org โ€บ cookbook โ€บ filter-an-array-based-on-condition
How to Filter an array based on condition in Swift | iSwift Cookbook
I have an array and want to filter its elements based on a defined condition. // Initialize the Array var a = [1,2,3,4,5,6] // Get only even numbers: X % 2 = 0 a = a.filter { $0 % 2 == 0 } print(a) ... *Apple, Swift and the Apple logo are trademarks of Apple Inc., registered in the U.S.
๐ŸŒ
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.
Top answer
1 of 3
4

You would have an easier time by simplifying and breaking up your code into smaller pieces. There's no reason why a function to filter an array by some conditions, also has to be responsible for figuring out if an element meets those conditions. You've mentally trapped yourself thinking that the filter predicate has be one one long chain of && conditions in a closure.

struct CarOffer {
    let brand: String
    let price: Int
    let color: String
    let consumption: Int
}

struct CarFilter {
    let brand: String?
    let price: Int?
    let consumption: Int?

    func matches(car: CarOffer) -> Bool {
        if let brand = self.brand, brand != car.brand { return false }
        if let price = self.price, price != car.price { return false }
        if let consumption = self.consumption, consumption != car.consumption { return false }
        return true
    }
}

extension Sequence where Element == CarOffer {
    func filter(carFilter: CarFilter) -> [CarOffer] {
        return self.filter(carFilter.matches)
    }
}

let filter = CarFilter(brand: nil, price: nil, consumption: nil)
let offers: [CarOffer] = [] //...
let filteredOffers = offers.filter(carFilter: filter)
2 of 3
3

You can simply use a default value instead of filters Optional values. If you use the default value of the offer, filter will simply return true in case the optional properties were nil.

func applyFilter(filter: Filter) -> [CarOffer] {

    let filteredOffers = offers.filter { $0.brand == filter.brand && $0.price <= (filter.price ?? $0.price) && $0.consumption <= (filter.consumption ?? $0.consumption) }

    return filteredOffers
}
๐ŸŒ
TutorialKart
tutorialkart.com โ€บ swift-tutorial โ€บ swift-array-filter
How to Filter a Swift Array based on a Condition?
May 2, 2021 - Only those elements that satisfy the given condition, or return true for the given condition, will make it to the resulting array. In the following program, we will take an array of numbers, and filter only those numbers that are greater than 10. ... var arr = [1, 99, 6, 74, 5] let result = arr.filter { $0 > 10 } print("Original Array : \(arr)") print("Filtered Array : \(result)") ... Concluding this Swift Tutorial, we learned how to filter a given array based on a specific condition.
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 49206854 โ€บ filter-multiple-arrays-with-one-condition โ€บ 49207512
swift - Filter multiple arrays with one condition - Stack Overflow
var categoryItemUIDs = ["aaa","bbb","ccc"] var categoryItemDescriptions = ["ddd","eee","fff"] var categoryItemLfdNrs = [0,1,2] struct data { var id = "" var desc = "" var item = 0 init(id :String, desc:String, item:Int) { self.id = id self.desc = desc self.item = item } } //var cat = [data]() //for i in 0..<categoryItemUIDs.count { // cat.append(data(id:categoryItemUIDs[i], desc:categoryItemDescriptions[i],item:categoryItemLfdNrs[i] )) //} //more swift let cat = (0..<categoryItemUIDs.count).map { (i) -> data in return data(id:categoryItemUIDs[i], desc:categoryItemDescriptions[i],item:categoryItemLfdNrs[i] ) } print (cat) let catFilter = cat.filter { $0.id == "aaa" } print (catFilter) ... The December 2024 Community Asks Sprint has been moved to March 2025 (and... Stack Overflow Jobs is expanding to more countries ยท 1 Scanning all/specific arrays values when filtering an array of arrays
Top answer
1 of 2
1

First of all I made a little bit changes to your model:

struct Student {
    var fName: String?
    var lname: String?
    var `class`: String?
    var pincode: Int?
    var active: Bool
    var location: Address
}
struct Address {
    var street1: String?
    var street2: String?
    var country: String?
}

Building dummy objects:

let address1 = Address(street1: "Kiwi str", street2: nil, country: "US")
let address2 = Address(street1: "Cherry str", street2: nil, country: "GB")
let student1 = Student(fName: "Mark", lname: nil, active: false, location: address1)
let student2 = Student(fName: "Diana", lname: "Luck", active: true, location: address2)
let student3 = Student(fName: "Gaga", lname: "Merry", active: true, location: address2)
let student4 = Student(fName: "Mark", lname: "Luck", active: true, location: address1)

let students = [student1, student2, student3, student4]
 

Filtering extension on Array with students elements:

extension Array where Element == Student {
    func filtered(fName: String? = nil, lName: String? = nil, active: Bool? = nil, street1: String? = nil) -> [Student] {
        students.filter { student in
            var fNameOk = false
            if let fName = fName, student.fName == fName {
                fNameOk = true
            }
            
            var lNameOk = false
            if let lName = lName, student.lname == lName {
                lNameOk = true
            }
            
            var activeOk = false
            if let active = active, student.active == active {
                activeOk = true
            }
            
            var street1Ok = false
            if let street1 = street1, student.location.street1 == street1 {
                street1Ok = true
            }
            return (
                (fName == nil ? true : fNameOk) &&
                (lName == nil ? true : lNameOk) &&
                (active == nil ? true : activeOk) &&
                (street1 == nil ? true : street1Ok)
            )
        }
    }
}

Testing filtering extension:

let r1 = students.filtered(fName: "Diana", lName: "Luck", active: true)
let r2 = students.filtered(fName: "Mark", active: true, street1: "Kiwi str")

Test output:

// r1
{fName "Diana", lname "Luck", nil, nil, active true, {street1 "Cherry str", nil, country "GB"}}
// r2
{fName "Mark", lname "Luck", nil, nil, active true, {street1 "Kiwi str", nil, country "US"}}
2 of 2
0

Fixing code by Ramis so it would compile and would be more straightforward without unnecessary checking of nil values. Also, if one condition is false, it returns false immediately.

extension Array where Element == Student {
    func filter(fName: String? = nil, active: Bool? = nil, street1: String? = nil) -> [Student] {
        filter { student in
            
            if let fName = fName, student.fName != fName {
                return false
            }
            
            if let active = active, student.active != active {
                return false
            }
            
            if let street1 = street1, student.location.street1 != street1 {
                return false
            }
            
            return true
        }
    }
}

Usage would be i.e.:


let address1 = Address(street1: "Kiwi str", street2: nil, country: "US")
let address2 = Address(street1: "Cherry str", street2: nil, country: "GB")
let student1 = Student(fName: "Mark", lname: nil, active: false, location: address1)
let student2 = Student(fName: "Diana", lname: "Luck", active: true, location: address2)
let student3 = Student(fName: "Gaga", lname: "Merry", active: true, location: address2)
let student4 = Student(fName: "Mark", lname: "Luck", active: true, location: address1)

let students = [student1, student2, student3, student4]

let filtered1 = students.filter(fName: "Diana", active: true)
let filtered2 = students.filter(fName: "Mark")
๐ŸŒ
DhiWise
dhiwise.com โ€บ post โ€บ efficient-data-refinement-with-swift-array-filter-strategies
Mastering Swift Array Filter: A Comprehensive Guide
September 10, 2024 - 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.
๐ŸŒ
Linux Hint
linuxhint.com โ€บ swift-array-filter
Swift Array โ€“ Filter()
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
๐ŸŒ
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.
๐ŸŒ
Bugfender
bugfender.com โ€บ blog โ€บ swift-arrays
Swift Arrays: Map, Filter, Reduce & Sort Explained | Bugfender
November 7, 2025 - Another essential Swift array operation is filtering. This allows us to zoom into the elements that meet specific conditions, and extract only them.
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])}
๐ŸŒ
Packtpub
subscription.packtpub.com โ€บ book โ€บ programming โ€บ 9781787120396 โ€บ 7 โ€บ ch07lvl1sec86 โ€บ filtering-arrays-with-complex-conditions
Filtering arrays with complex conditions
Access over 7,500 Programming & Development eBooks and videos to advance your IT skills. Enjoy unlimited access to over 100 new titles every month on the latest technologies and trends