本文介绍了如何比较两个对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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]

我不知道哪种方式最好check:
array1 == array2 if a1.identifier == a5.identifier,a2.identifier == a6.identifier,a3.identifier == a7.identifier,a4.identifier == a8 Swide中的.identifier

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.identifier in Swift.

请帮帮我...

推荐答案

假设您的数据如下:

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为两个人的数组:

This is the method to compare two arrays of people with 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
}

这篇关于如何比较两个对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:22