Skip to content

Commit

Permalink
Fix RealmSwift List equality
Browse files Browse the repository at this point in the history
Fix realm#5665 by overriding isEqual for RealmSwift.List to compare elements.
  • Loading branch information
phlippieb committed May 25, 2020
1 parent 46cd7e8 commit 9933e50
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions RealmSwift/List.swift
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,14 @@ public final class List<Element: RealmCollectionValue>: ListBase {
@objc class func _unmanagedArray() -> RLMArray<AnyObject> {
return Element._rlmArray()
}

public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? List<Element> else { return false }
guard self.count == other.count else { return false }

return zip(self, other)
.reduce(true) { $0 && ($1.0 == $1.1) }
}
}

extension List where Element: MinMaxType {
Expand Down
26 changes: 26 additions & 0 deletions RealmSwift/Tests/ListTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -792,4 +792,30 @@ class ListRRCMethodsTests: TestCase {
array.replaceSubrange(subrange, with: newElements)
compare(array: array, with: list)
}

func testRealmListOfStringsComparison() {
// Lists made from identical arrays should be equal:
let strings = ["a", "b", "c"]
let list1 = List<String>()
list1.append(objectsIn: strings)

let list2 = List<String>()
list2.append(objectsIn: strings)

XCTAssertTrue(list1 !== list2, "instances should not be identical")
XCTAssertTrue(list1 == list2, "instances should be equal by `==` operator")
XCTAssertTrue(list1.isEqual(list2), "instances should be equal by `isEqual` method")
XCTAssertTrue(Array(list1) == Array(list2), "instances converted to Swift.Array should be equal")

// Lists made from different-length arrays should not be equal,
// even if the common elements are equal.
let strings2 = ["a", "b", "c", "d"]
let list3 = List<String>()
list3.append(objectsIn: strings2)

XCTAssertTrue(list1 !== list3, "instances should not be identical")
XCTAssertFalse(list1 == list3, "instances should not be equal by `==` operator")
XCTAssertFalse(list1.isEqual(list3), "instances should not be equal by `isEqual` method")
XCTAssertFalse(Array(list1) == Array(list3), "instances converted to Swift.Array should not be equal")
}
}

0 comments on commit 9933e50

Please sign in to comment.