How to Extract an Object by Property Value from an Array in Swift

Have you ever had an array of Swift objects and wanted to retrieve an object with a specific ID or another property value?

For example, suppose you have an array of [Employee] structs like this, and you want to retrieve the Employee object with employeeID = 3.

struct Employee {
    var employeeID: Int
    var firstName: String
    var lastName: String
}

Here, we assume a case where only one object matching the condition exists in the array.

In this article, I'll explain how to extract an object from an array of Swift objects by specifying the value of a property.


How to Retrieve an Object from an Array in Swift by Property Value

If you want to filter an array in Swift by specifying a value such as an ID and retrieve the corresponding object, you can use the Array's first method.

You can use it like this: Array.first(where: { condition })

The first method returns the first element that matches the condition, or nil if no element is found.


Here's a sample code that retrieves an object with a specified ID from an array of struct objects:

struct Employee {
    var employeeID: Int
    var firstName: String
    var lastName: String
}

var employees: [Employee] = []
employees.append(Employee(employeeID: 1, firstName: "Olivia", lastName: "Smith"))
employees.append(Employee(employeeID: 2, firstName: "James", lastName: "Johnson"))
employees.append(Employee(employeeID: 3, firstName: "Noah", lastName: "Williams"))
employees.append(Employee(employeeID: 4, firstName: "Jack", lastName: "Brown"))
employees.append(Employee(employeeID: 5, firstName: "Evelyn", lastName: "Jones"))

if let emp = employees.first(where: { $0.employeeID == 3 }) {
    print(emp.employeeID, emp.firstName, emp.lastName)
} else {
    print("Not found")
}

Lines 7 to 12 create an array containing Employee struct objects.

In line 14, using if let together with the array's first method, we retrieve the Employee object with employeeID == 3 from employees.

$0 represents the first argument of the closure. Since $0 is of type Employee, specifying $0.employeeID == 3 evaluates to true when the employeeID equals 3.

If a matching Employee object is found, its employeeID, firstName, and lastName are printed. If none is found, "Not found" is printed.


When you run the code above, the output will be:

3 Noah Williams

Swift - How to extract an object with a specified property value from an array 1


The employeeID, firstName, and lastName for the employee with employeeID = 3 are printed.

If you change line 14 to $0.employeeID == 6 and run it, "Not found" will be printed.

Swift - How to extract an object with a specified property value from an array 2


That's how you can retrieve an object with a specified property value from an array in Swift.