Equatable or comparable with two array of same object

I have two array and want to check equality of these two objects

class test {

var val: String?

var val1: String?

init(data: JSON) {

val = data["val"].stringValue

val1 = data["val1"].stringValue

}

}

var arr1 = [test]()

var arr2 = [test]()

arr1== arr2

Note:- classes can have multiple variables and I want a generic solution.

Could you format the text of your post to make it more readable ?


Where do you define JSON type ?

Why do tou use stringValue (because of this, JSON must be declared with AnyObject)


You have to define == func and != fun and declare class as Equatable.


Here is code, where I defined the JSON type


typealias JSON = [String: AnyObject]

class test: Equatable {
   
    var val: String?
    var val1: String?
   
    init(data: JSON) {
        val = data["val"]?.stringValue ?? "0"
        val1 = data["val1"]?.stringValue  ?? "0"
    }
   
    static func ==(lhs: test, rhs: test) -> Bool {
        if (lhs.val == nil && rhs.val != nil) { return false }
        if (lhs.val1 == nil && rhs.val1 != nil) { return false }
        if (lhs.val != nil && rhs.val == nil) { return false }
        if (lhs.val1 != nil && rhs.val1 == nil) { return false }
        if lhs.val == nil && rhs.val == nil && lhs.val1 == nil && rhs.val1 == nil { return true }
        return (lhs.val == nil && rhs.val == nil && lhs.val1 == nil && rhs.val1 == nil) || ((lhs.val! == rhs.val!) && (lhs.val1! == rhs.val1!))

    }
   
    static func !=(lhs: test, rhs: test) -> Bool {
        return !(lhs == rhs)
    }

}

Multiple tests for nil in == could be simplified with statements as

let left = lhs.val ?? "-"

let left1 = lhs.val1 ?? "-"

Then, no more need to unwrap and risk crash.

    static func ==(lhs: test, rhs: test) -> Bool {
       
        let left = lhs.val ?? "-"
        let left1 = lhs.val1 ?? "-"
        let right = rhs.val ?? "-"
        let right1 = rhs.val1 ?? "-"
        return (left == right) && (left1 == right1)
    }

this working only in this case like

arr1[0] == arr2[0]

arr1[1] == arr1[1]

this is already done by me but i want to compare any type of array.

What do you mean any type of array ?


if the base class is equatable, then you can compare arrays.


For instance here, you can test:


        let someTestData1 = test(data: ["val": 1 as AnyObject])
        let someTestData2 = test(data: ["val1": 2 as AnyObject])
        let someTestData3 = test(data: ["val": 3 as AnyObject])
        let someTestData4 = test(data: ["val1": 4 as AnyObject])

        var arr1 = [test]()
        arr1 = [someTestData1, someTestData3]
        var arr2 = [test]()
        arr2 = [someTestData2, someTestData4]
        print("Equal", arr1 ==  arr2)

        arr1 = [someTestData1, someTestData2]
        arr2 = [someTestData1, someTestData2]
        print("new test Equal", arr1 ==  arr2)

you get

Equal false

new test Equal true


note: your class names (eg test) should start with uppercase

equatable protocol not works on Array What do you mean any type of array ? this means that

var arr1 = [test]()

var arr2 = [test]()

arr1 == arr2

var arr3 = [test11]()

var arr4 = [test11]()

arr3 == arr4

Or you can say that comparing two array having the same class can i create any generic solution of it ?

Once again, if Test11 is equatable, it will work (in Swift 4.1 or over).

i tried if i check single object then it works but on complete array it doesn't

Can you show exactly how you test ? And result that fails.


Take care that arrays are ordered, so if the 2 arrays are not in the same order, result will be false.


In that case you could sort the arrays first (need to define a sort function).

inside class Test


    func isBefore(_ other: test) -> Bool {
        if self == other { return true }
      
        if self.val! < other.val! { return true }
        if self.val! > other.val! { return false }
        if self.val1! < other.val1! { return true }
        if self.val1! > other.val1! { return false }
        return true // Cannot happen
    }

Then call

       arr1 = [someTestData1, someTestData2]
        arr2 = [someTestData2, someTestData1]
        print("new test Sorted", arr1.sorted { $0.isBefore($1) } ==  arr2.sorted { $0.isBefore($1) })


yields true

new test Sorted true

one array I am fetching from the realm database and another one I get from API then comparing these arrays getting result false and when I Iterate array and matches each object of an array then getting the result true

Please, show the code.


How do you compare object by object ? Are yoy type casting one of them ?

I am using Realm

var test1 = Array<Test>()

if let array = data["data"].array {

self.test1 = array.map { Test(data: $0) }



}

do {

try DBManager.sharedInstance?.database.write {

if var val = DBManager.sharedInstance?.database.objects(Test.self) {

let test = Array(val)

if self.test1[0] == test[0] {

// this gives true

}



if self.test1 == test {

// this gives false

}



}

}

}

catch let error {

print("cannot perform the operation - \(error)")

}



final class Test: Object {




@objc dynamic var val: String?

@objc dynamic var val1: String?


convenience init (data: JSON) {

self.init()

self.val = data["val"].stringValue

self.val1 = data["val1"].stringValue

}


public static func == (lhs: BannerSet, rhs: BannerSet) -> Bool {



return

lhs.val1 == rhs.val1 &&

lhs.val == rhs.val

}


override static func primaryKey() -> String? {

return "val"

}

}

What is the content of data["data"].array ?


Could you print

     print(self.test1, test) //   to see exactly what they are.


Before doing the following test

                    if self.test1 ==  test {
                      // this gives false
                    }

What is the content of data["data"].array ? this contains this class data class Test: Object Could you print yes these are same

What is the content of data["data"].array ?

this contains this class data class Test: Object

Yes, of course. That was not the question. Question was to see the exact content dump.


Could you print

yes these are same

That is exactly what need to be checked. If you are sure things are the same, then no use to ask question !


So, if you really want someone to try and help you,

- Would you mind copy and paste the result of the print ?

- And show the complete code of the class ?


Otherwise, ask the question to Realm support, that means there is something wrong or that you misuse there.

Equatable or comparable with two array of same object
 
 
Q