如何比较两个对象数组?

时间:2016-08-26 07:54:44

标签: ios arrays swift compare

我有一个A类:

class A {
   var identifier: String?
   var quantity: Int = 0
}

两个A实例数组:

var array1: [A] = [a1, a2, a3, a4]
var array2: [A] = [a5, a6, a7, a8]

我不知道哪种检查方式最好: 斯威夫特的array1==array2 if a1.identifier == a5.identifier, a2.identifier == a6.identifier, a3.identifier==a7.identifier, a4.identifier==a8.identifier

请帮帮我......

7 个答案:

答案 0 :(得分:23)

您可以尝试这样:

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

答案 1 :(得分:9)

假设您的数据如下:

struct Person
    {
        let name: String
        let id:  Int
    }

    var people1 = [
        Person(name: "Quang Hà", id: 42),
        Person(name: "Lý Hải", id: 23),
        Person(name: "Maria", id: 99)
    ]

    var people2 = [
        Person(name: "Maria yyy", id: 99),
        Person(name: "Billy", id: 42),
        Person(name: "David", id: 23)
    ]

这是比较具有id:

的两个人数组的方法
func areArrayPeopleEqual(people1:[Person], people2: [Person]) -> Bool {
    var array1 = people1
    var array2 = people2

    // Don't equal size => false
    if array1.count != array2.count {
        return false
    }

    // sort two arrays
    array1.sortInPlace() { $0.id > $1.id }
    array2.sortInPlace() {$0.id > $1.id }

    // get count of the matched items
    let result = zip(array1, array2).enumerate().filter() {
        $1.0.id == $1.1.id
        }.count

    if result == array1.count {
        return true
    }

    return false
}

答案 2 :(得分:3)

首先,我们扩展Equatable类,以获得 DRY 代码,而不是2个数组总是具有相同的大小,或者至少第一个是< = than第二,你可以使用这个解决方案。

请注意您正在使用选项,您可能需要先解开它们。

class A {
    var identifier: String?
    var quantity: Int = 0

    init(identifier: String, quantity: Int) {
        self.identifier = identifier
        self.quantity = quantity
    }
}

let a1: A = A(identifier: "1", quantity: 1)
let a2: A = A(identifier: "2", quantity: 2)
let a3: A = A(identifier: "3", quantity: 3)
let a4: A = A(identifier: "4", quantity: 4)

let a5: A = A(identifier: "1", quantity: 1)
let a6: A = A(identifier: "2", quantity: 2)
let a7: A = A(identifier: "3", quantity: 3)
let a8: A = A(identifier: "4", quantity: 4)

var array1: [A] = [a1, a2, a3, a4]
var array2: [A] = [a5, a6, a7, a8]

func areEquals(array1: [A], array2: [A]) -> Bool {
    if array1.count < array2.count {
        return false
    }
    for i in 0...array2.count - 1 {
        if array1[i] != array2[i] {
            return false
        }
    }
    return true
}


extension A: Equatable {
    static func ==(lhs: A, rhs: A) -> Bool {
        //you can choose how and when they should be equals
        return lhs.identifier == rhs.identifier
    }
}

Proof of working

答案 3 :(得分:2)

快捷键4

以下方法使其变得更加简单。

方法1-使用平等协议

第1步-如下使类'A'等于

extension A: Equatable {
    static func ==(lhs: A, rhs: A) -> Bool {
        // Using "identifier" property for comparison
        return lhs.identifier == rhs.identifier
    }
}

第二步-按升序或降序对数组进行排序

let lhsArray = array1.sorted(by: { $0.identifier < $1.identifier })
let rhsArray = array2.sorted(by: { $0.identifier < $1.identifier })

第3步-使用==或elementsEqual比较

let isEqual = lhsArray == rhsArray

OR

let isEqual = lhsArray.elementsEqual(rhsArray, by: { $0 == $1} )

方法2(无平等协议)

步骤1-按照方法1,步骤2中所述对数组进行排序

第2步-使用elementsEqual

lhsArray.elementsEqual(rhsArray, by: { $0.identifier == $1.identifier })

详细了解Array Comparison here

答案 4 :(得分:1)

试试这段代码,让我知道它是否有效

func toDictionary<E, K, V>(
    array:       [E],
    transformer: (element: E) -> (key: K, value: V)?)
    -> Dictionary<K, V>
{
    return array.reduce([:]) {
        (var dict, e) in
        if let (key, value) = transformer(element: e)
        {
            dict[key] = value
        }
        return dict
    }
}

然后您可以执行如下所示的检查

let areEqual = array1.count == array2.count;
if areEqual {
    let dict1 = toDictionary(array1) { ($0.identifier, $0.quantity) }
    let dict2 = toDictionary(array2) { ($0.identifier, $0.quantity) }
    areEqual = NSDictionary(dictionary: dict1).isEqualToDictionary(dict2)
}
print(areEqual)

免责声明:功能toDictionary已采用here

形式

答案 5 :(得分:1)

我在http://x.x.x.x.etc/signin-google

找到了一个非常简单的解决方案
extension Array where Element: Hashable {
func difference(from other: [Element]) -> [Element] {
    let thisSet = Set(self)
    let otherSet = Set(other)
    return Array(thisSet.symmetricDifference(otherSet))
}

}

let names1 = ["a1", "A4", "a3", "a4"]//["John", "Paul", "Ringo"]
let names2 = ["a1", "a5", "a4","a1.1"]//["Ringo", "George"]
let difference = names1.difference(from: names2)

答案 6 :(得分:1)

如果您有一些要比较的参数,则可以使用此方法:

let difference = currentObjects
    .filter({ currentObject in
        !(newObjects
            .contains(where: { $0.identifier == currentObject.identifier }))
    })