Skip to content

Commit 9933e50

Browse files
committed
Fix RealmSwift List equality
Fix realm#5665 by overriding isEqual for RealmSwift.List to compare elements.
1 parent 46cd7e8 commit 9933e50

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

RealmSwift/List.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,14 @@ public final class List<Element: RealmCollectionValue>: ListBase {
436436
@objc class func _unmanagedArray() -> RLMArray<AnyObject> {
437437
return Element._rlmArray()
438438
}
439+
440+
public override func isEqual(_ object: Any?) -> Bool {
441+
guard let other = object as? List<Element> else { return false }
442+
guard self.count == other.count else { return false }
443+
444+
return zip(self, other)
445+
.reduce(true) { $0 && ($1.0 == $1.1) }
446+
}
439447
}
440448

441449
extension List where Element: MinMaxType {

RealmSwift/Tests/ListTests.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -792,4 +792,30 @@ class ListRRCMethodsTests: TestCase {
792792
array.replaceSubrange(subrange, with: newElements)
793793
compare(array: array, with: list)
794794
}
795+
796+
func testRealmListOfStringsComparison() {
797+
// Lists made from identical arrays should be equal:
798+
let strings = ["a", "b", "c"]
799+
let list1 = List<String>()
800+
list1.append(objectsIn: strings)
801+
802+
let list2 = List<String>()
803+
list2.append(objectsIn: strings)
804+
805+
XCTAssertTrue(list1 !== list2, "instances should not be identical")
806+
XCTAssertTrue(list1 == list2, "instances should be equal by `==` operator")
807+
XCTAssertTrue(list1.isEqual(list2), "instances should be equal by `isEqual` method")
808+
XCTAssertTrue(Array(list1) == Array(list2), "instances converted to Swift.Array should be equal")
809+
810+
// Lists made from different-length arrays should not be equal,
811+
// even if the common elements are equal.
812+
let strings2 = ["a", "b", "c", "d"]
813+
let list3 = List<String>()
814+
list3.append(objectsIn: strings2)
815+
816+
XCTAssertTrue(list1 !== list3, "instances should not be identical")
817+
XCTAssertFalse(list1 == list3, "instances should not be equal by `==` operator")
818+
XCTAssertFalse(list1.isEqual(list3), "instances should not be equal by `isEqual` method")
819+
XCTAssertFalse(Array(list1) == Array(list3), "instances converted to Swift.Array should not be equal")
820+
}
795821
}

0 commit comments

Comments
 (0)