Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare elements of two arrays

Tags:

arrays

swift

I want to compare the elements of two arrays and check if they are equal. I already tried various solutions but nothing really works.

I tried the solution from How to compare two array of objects?

This is my object:

struct AccountBalance: Decodable {
    let balance: Double
    let currency: String

    init(balance: Double, currency: String ) {
        self.currency = currency
        self.balance = balance
    }

    enum CodingKeys: String, CodingKey {
        case currency = "Currency"
        case balance = "Balance"
    }
}

This is the code from the link I tried:

let result = zip(accountBalance, getsSaved).enumerate().filter() {
                $1.0 == $1.1
                }.map{$0.0}

But I get this error:

Closure tuple parameter '(offset: Int, element: (AccountBalance, AccountBalance))' does not support destructuring with implicit parameters
like image 881
PaFi Avatar asked Jan 17 '18 01:01

PaFi


People also ask

Can you use == for arrays?

For arrays, the equals() method is the same as the == operator. So, planes1. equals(planes2) returns true because both references are referring to the same object.


2 Answers

I will suggest you implement the accepted answer of the link you provided because it controls that both arrays are the same size and it orders them.

But if you want that your code works I solved like this:

enter image description here

In order to have control of the comparison your struct should implement the Equatable protocol and overload the operator ==

extension AccountBalance : Equatable {}

func ==(lhs: AccountBalance, rhs: AccountBalance) -> Bool {
    return lhs.balance == rhs.balance && lhs.currency == rhs.currency
}

Then compare both arrays and check if contains false, if it does, one or more items in the array aren't the same.

let result = !zip(accountBalance, getsSaved).enumerated().map() {
    $1.0 == $1.1
}.contains(false)

Hope it helps you

like image 68
omarzl Avatar answered Oct 04 '22 07:10

omarzl


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
}
like image 24
vadian Avatar answered Oct 04 '22 07:10

vadian