0

I have an issue while using filter method to compare two arrays. I don't get the same issue when I perform the same filter pattern in Playground. What's wrong with my code?

More details:

  1. Get users from URL and before saving I try to compare current array to new array from API:
func getUsersNetworking() {
        getUsersDatabase()
        manager.getUsers { [weak self] results in
            guard let self = self else { return }
            switch results {
            case .success(let users):
                // transfer data to compare:
                self.filterArrays(currentUsersFromDB: self.databaseUsers, newUsersFromNet: users)
                
                // Not relevant data to my issue:
                self.getUsersDatabase()
            case .failure(let error): print(error.localizedDescription)
            }
        }
    }
  1. method where error appears:
func filterArrays(currentUsersFromDB: [Users], newUsersFromNet: [Users]) {
        let users = newUsersFromNet.filter { currentUsersFromDB.contains($0)} // Error appears here!
        
        var array: [Users] = []
        array.append(contentsOf: users)
        database.saveUsersToDB(users: array)
    }

The Error message: Cannot convert value of type 'Users' to expected argument type '(Users) throws -> Bool'

chAOS
  • 11
  • 5
  • I suspect `Users` does not conform to `Equatable`, so `contains(Users)` is not available. Please conform `Users` to `Equatable`. – Sweeper Aug 28 '22 at 00:57
  • Does this answer your question? [How to check if an element is in an array](https://stackoverflow.com/questions/24102024/how-to-check-if-an-element-is-in-an-array) – Sweeper Aug 28 '22 at 10:26
  • Partly) My question was about checking two arrays to indicate a new elements in new one. Thanks. – chAOS Aug 28 '22 at 10:42

1 Answers1

0

As mentioned by Sweeper above, I just had to conform my User model to Equatable protocol. Read more detailed about Equatable protocol by the link: https://developer.apple.com/documentation/swift/equatable

my solution:

import Foundation

struct Users: Codable {
    let name: String
    let username: String
    let address: Address
}

struct Address: Codable {
    var geo: Geo
}

struct Geo: Codable {
    var lat: String
    var lng: String
}

// Add it to compare two arrays (new users with current users):
extension Users: Equatable {
    static func == (lhs: Users, rhs: Users) -> Bool {
        lhs.name == rhs.name &&
        lhs.username == rhs.username &&
        lhs.address.geo.lat == rhs.address.geo.lat &&
        lhs.address.geo.lng == rhs.address.geo.lng
    }
}
chAOS
  • 11
  • 5