How to compare elements of two arrays

Array provides a function elementsEqual which is able to compare two arrays without explicitly conforming to Equatable:

let result = accountBalance.elementsEqual(getsSaved) {
    $0.balance == $1.balance && $0.currency == $1.currency
}

Edit:

If you want to have the equality result regardless of the order of objects in the array then you can just add sort with each of the arrays.

let result = accountBalance.sorted { $0.balance < $1.balance }.elementsEqual(getsSaved.sorted { $0.balance < $1.balance }) {
    $0.balance == $1.balance && $0.currency == $1.currency
}

I am guessing two arrays should be considered equal when they contain the same elements, regardless of ordering.

First, implement Equatable and Hashable.

I am using hashValue as an id so I can sort the arrays first.

Here is what your AccountBalance class should look like:

struct AccountBalance: Decodable, Equatable, Hashable {


   // Important parts!
    var hashValue: Int{
        return balance.hashValue ^ currency.hashValue &* 1677619
    }
    static func == (lhs: AccountBalance, rhs: AccountBalance)  -> Bool{
        return lhs.balance == rhs.balance && lhs.currency == rhs.currency
    }

}

Then create an algorithm that sorts the ararys and then check each elements by one by by if the contents are the same.

Here is the function that take use of Equatable and Hashable.

func isEqual(arr1: [AccountBalance], arr2: [AccountBalance]) -> Bool{

    if arr1.count != arr1.count{
        return false
    }

    let a = arr1.sorted(){
        $0.hashValue > $1.hashValue
    }

    let b = arr2.sorted(){
        $0.hashValue > $1.hashValue
    }

    let result = zip(a, b).enumerated().filter() {
        $1.0 == $1.1
        }.count

    if result == a.count{
        return true
    }

    return false
}

Tags:

Arrays

Swift