ios 如何比较两个对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39161168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:59:53  来源:igfitidea点击:

How to compare two array of objects?

iosarraysswiftcompare

提问by Quang Hà

I have a class A:

我有一个A类:

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

Two arrays of A instances:

A 实例的两个数组:

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

I don't know which is the best way to check: array1==array2 if a1.identifier == a5.identifier, a2.identifier == a6.identifier, a3.identifier==a7.identifier, a4.identifier==a8.identifierin Swift.

我不知道哪种检查方式最好: array1==array2 if a1.identifier == a5.identifier, a2.identifier == a6.identifier, a3.identifier==a7.identifier, a4.identifier==a8.identifier在 Swift 中。

Please help me...

请帮我...

回答by Rahul Tripathi

You can try like this:

你可以这样试试:

let result = zip(array1, array2).enumerated().filter() {
    .0 == .1
}.map{
struct Person
    {
        let name: String
        let id:  Int
    }

    var people1 = [
        Person(name: "Quang Hà", id: 42),
        Person(name: "Ly 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)
    ]
.0}

回答by t4nhpt

Assume your data like that:

假设你的数据是这样的:

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() { 
extension A: Equatable {
    static func ==(lhs: A, rhs: A) -> Bool {
        // Using "identifier" property for comparison
        return lhs.identifier == rhs.identifier
    }
}
.id > .id } array2.sortInPlace() {
let lhsArray = array1.sorted(by: { 
let isEqual = lhsArray == rhsArray
.identifier < .identifier }) let rhsArray = array2.sorted(by: {
let isEqual = lhsArray.elementsEqual(rhsArray, by: { 
lhsArray.elementsEqual(rhsArray, by: { 
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
    }
}
.identifier == .identifier })
== } )
.identifier < .identifier })
.id > .id } // get count of the matched items let result = zip(array1, array2).enumerate().filter() { .0.id == .1.id }.count if result == array1.count { return true } return false }

This is the method to compare two arrays of people with id:

这是比较两个具有 id 的人数组的方法:

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
    }
}

回答by Anand

Swift 4

斯威夫特 4

The following method makes it much more easy.

下面的方法使它更容易。

Method 1 - Using Equatable Protocol

方法 1 - 使用 Equatable 协议

Step1 - Make your class 'A' equatable as follows

步骤 1 - 使您的类“A”相等,如下所示

let areEqual = array1.count == array2.count;
if areEqual {
    let dict1 = toDictionary(array1) { (
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)
.identifier, ##代码##.quantity) } let dict2 = toDictionary(array2) { (##代码##.identifier, ##代码##.quantity) } areEqual = NSDictionary(dictionary: dict1).isEqualToDictionary(dict2) } print(areEqual)

Step2 - Sort your arrays in ascending or descending order

Step2 - 按升序或降序对数组进行排序

##代码##

Step3 - Use == or elementsEqual comparison

Step3 - 使用 == 或 elementsEqual 比较

##代码##

OR

或者

##代码##

Method 2 (Without Equatable Protocol)

方法 2(无 Equatable 协议)

Step 1 - Sort Array as described in Method1, step 2

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

Step 2 - Use elementsEqual

第 2 步 - 使用 elementsEqual

##代码##

Read more about Array Comparison here

在此处阅读有关数组比较的更多信息

回答by Andrea Miotto

First we extend Equatableclass, to have a DRYcode, than if the 2 arrays are always of the same size, or if at least the first one is <= than the second you can go with this solution.

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

Pay attention that you are working with optionals, you may have to unwrap them before.

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

##代码##

Proof of working

工作证明

回答by ddb

try this code, let me know if it works

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

##代码##

then you can execute a check like below

然后您可以执行如下检查

##代码##

disclaimer: function toDictionaryhas been took form here

免责声明:功能toDictionary已经在这里形成