WWDC24 deal: 30% off our Swift and SwiftUI books! Learn more ...WWDC24 deal:30% off our Swift and SwiftUI books >>
Quick Tip Icon
Quick Tip

Compare arrays based on custom criteria

When we need to compare arrays based on custom criteria in Swift, we can use elementsEqual(_:by:) method. This method allows us to define how two arrays should be compared, offering more flexibility than using == operator with arrays of Equatable elements.

Here's a practical example:

struct Employee {
    let name: String
    let age: Int
    let role: String
}

let employees1 = [
    Employee(name: "Alice", age: 30, role: "Engineer"),
    Employee(name: "Bob", age: 25, role: "Designer")
]

let employees2 = [
    Employee(name: "Charlie", age: 28, role: "Engineer"),
    Employee(name: "Dave", age: 32, role: "Designer")
]

// Custom comparison logic: compare based on role only
let areRolesEqual = employees1.elementsEqual(employees2) {
    $0.role == $1.role
}
print(areRolesEqual) // true

In this example, we compare two lists of employees based solely on their roles, ignoring names and ages. This is particularly useful for scenarios where specific comparison logic is required temporarily or for a particular use case.

Using elementsEqual(_:by:), we can define custom comparison logic with a closure, making it easy to switch criteria without modifying the Employee struct itself. This method is ideal for single-use scenarios where conforming array elements to Equatable might be unnecessary or inappropriate.

For more advanced Swift tips and techniques, check out my new book, Swift Gems. From optimizing collections and handling strings to mastering asynchronous programming and debugging, "Swift Gems" provides practical advice to elevate your Swift development. Grab your copy and let's explore these advanced techniques together.

Books by Natalia PanferovaBooks by Natalia Panferova
WWDC24: 30% off all books!
  • Swift Gems

    100+ tips to take your Swift code to the next level

  • Integrating SwiftUI into UIKit Apps

    A detailed guide on gradually adopting SwiftUI in UIKit projects

The offer is active until the 16th of June.