Filter Array in Swift based on multiple properties

swift filter multiple conditions
swift filter array of strings
swift reduce
swift array functions
swift map
filter array of dictionary swift 4
swift reduce dictionary
struct User{
    var firstName:String
    var lastName:String
    var city:String
    var email:String

var users = [User]

I am trying to filter users as someone is typing in the textfield. Its like Search for the email. It should show all the matching results but shouldn’t duplicate the same user. I am able to filter the array based on one property such as name but not sure how to filter the array based on all the properties.

I’ve implemented the UITextField delegate and have this code for filtering.

let filteredArray = users.filter({ (user) -> Bool in
    return user.firstName.lowercased().contains("John")
let filteredArray = users.filter({ $0.firstName.lowercased().contains("firstName") || $0.lastName.lowercased().contains("lastName") || ... })

Filtering arrays with complex conditions, Declaring a class that conforms to multiple protocols Adding computed properties to a base type with extensions In this case, the getAll method returns an array of Game instances, which we can use with the filter method The code calls the getAll and filter methods for the result with a closure that specifies the required  Filter an array based on condition. Problem. I have an array and want to filter its elements based on a defined condition. Recipe // 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)

You can set multiple conditions and combine them together with OR (||) or AND (&&)- its a simple boolean, you can think of it as it was in an if statement-

if user.firstName.lowercased().contains("john") || user.lastName.lowerCased().contains("lastname") { return true }
else { return false }

so in your code it will be like

let filteredArray = users.filter { (user) -> Bool in
return user.firstName.lowercased().contains("john") || user.lastName.lowercased().contains("lastname") }

Filters an array of objects with multiple match-criteria. · GitHub, and its value is a function with the value of the property to evaluate. Filters an array of objects (one level-depth) with multiple criteria. Supporting array and also object as the filter criteria not only increase the base-code but also the current  * Filter an array of objects. * You can pass in one or more properties on which to filter. * If the key of an array is an array, then it will filtered down to that

Since you'll probably need to search multiple things, I would recommend you make a Searchable protocol, and make aggregate types searchable by virtue of checking if any of their constituents match.

import Foundation

struct User {
    let firstName: String
    let lastName: String
    let city: String
    let email: String
    let age: Int // an example of a non-String type.

protocol Searchable {
    func matches(query: String) -> Bool 

extension String: Searchable {
    func matches(query: String) -> Bool {
        // Implement any kind of searching algorithm here. Could be as smart as fuzzy seraching
        // or as basic as this case-insenitive simple substring search
        return self.lowercased().contains(query)

extension Int: Searchable {
    func matches(query: String) -> Bool {
        return String(self).matches(query: query)

extension User: Searchable {
    func matches(query: String) -> Bool {
        let constituents: [Searchable] = [firstName, lastName, city, email, age]
        return constituents.contains(where: { $0.matches(query: query) })

Swift Recipes: A Problem-Solution Approach, filter on one property var results = complexArray.filter({ v in v.year >= 2008 }) // filter on multiple properties var moreResults = complexArray.filter( { v in v.year > The function must return a Boolean based on the criteria you specify for ordering. The filter swift function allows us to define which field of our custom object to filter, number in this case. Use the sort function to order the list on the basis of a custom object properties We'll now need to order the list, by putting the number in an ascending order. By using the sort function we'll able to do that.

Filtering using functions as parameters, This will work by giving PlayData a new array, filteredWords , that will store all words that matches Start by adding this filteredWords property to PlayData : Swift has a built-in way to find out whether a string contains an integer, because it​  Swift makes it easy to create arrays in your code using an array literal: simply surround a comma-separated list of values with square brackets. Without any other information, Swift creates an array that includes the specified values, automatically inferring the array’s Element type.

Language - free Swift 5.1 example code, Swift has built-in way of checking whether all items in an array match a condition: the initializer, which is an initializer that accepts values for all the properties in the struct. How to break out of multiple loop levels using labeled statements. Swift The filter() method goes over all the items in an array (or indeed any kind of  Summary: in this tutorial, you will learn how to use the JavaScript Array filter() method to filter elements in an array.. Introduction to JavaScript array filter() method. One of the most common tasks when working with an array is to create a new array that contains a subset of elements of the original array.

Filtering array of objects by strings in another array. : swift, r/swift: Swift is a general-purpose programming language built using a modern I have an array of Match objects [Match] with a string property of matchID. 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. For example, given the following array: let numbers = [1, 2, 4, 7, 9, 12, 13] We could use filter() to create an array of all the numbers that are greater than or equal to 5:

  • Possible duplicate of Filter by multiple array conditions
  • Let's think about what's the meaning of the filter() closure. You iterate the array, the current element is named in your case user (that's the param). Then, according to user values, you decide to return true if you want to keep it, and false if you don't. Currently, you return true if the firstName.lowercased() contains "John". So check on the other property using an OR between them?
  • @Larme I never thought of using OR. You are right. Thanks
  • You can use AND also, it really depends on what's the reason to keep the element or not. It can be a "complicated" reason.
  • Use or (||) if you want to increase the number of matches. Use and (&&) if you only want to match items that meet ALL the criteria.
  • that's a very long line. It's better to split it up.
  • don't do if b { return true } else { return false }. Just do return b.
  • It doesn't clarify anything. It just adds irrelevant redundancy
  • It does because this syntax might be confusing for starting programmers, so I converted it to a simple if statement. A lot of starters have problems understanding that if statement is actually consist from a boolean
  • From that perspective (of the absolute beginner), your code is strictly more complex. It requires understanding booleans, if statements and return statements, whereas my suggested code only requires understanding return statements.
  • beginners don't consider "user.firstName.lowercased().contains("john") || user.lastName.lowerCased().contains("lastname")" as a single boolean parameter "b"