如何基于另一个数组元素属性快速对数组进行排序

时间:2018-12-10 16:39:48

标签: arrays swift sorting

所以,我有这些数组:

let persons = [{idPerson: 4, name: "John"}, {idPerson: 2, name: "Bill"}, {idPerson: 3, name: "Vivian"}, {idPerson: 1, name: "Max"}]
let positions = [{idPerson: 1, value: 5}, {idPerson: 2, value:6}, {idPerson: 3, value: 7}, {idPerson: 4, value: 8}]

我想基于 positions 数组,通过属性 value 对数组 persons 进行排序。

idPerson 是连接两个阵列的属性。

如何做到最好?

1 个答案:

答案 0 :(得分:1)

struct PerosonRemote {
    var personID: Int
    var name: String
}

struct Position {
    var personID: Int
    var value: Int
}

struct Peroson {
    var value: Int
    var name: String
}

let personsRemote = [PerosonRemote(personID: 4, name: "John"),   
                     PerosonRemote(personID: 2, name: "Bill"), 
                     PerosonRemote(personID: 3, name: "Vivian"), 
                     PerosonRemote(personID: 1, name: "Max")]  

let positionsRemote = [Position(personID: 1, value: 5),
                       Position(personID: 2, value: 6),
                       Position(personID: 3, value: 7),
                       Position(personID: 4, value: 8)]

func getValue(forPersonID id: Int) -> Int {
    for position in positionsRemote {
        if position.personID == id {
            return position.value
        }
    }

    return 0 // Not found PersonID
}


var persons = [Peroson]()

personsRemote.forEach { (person) in
    persons.append(Peroson(value: getValue(forPersonID: person.personID), name:     person.name))
}

var sortedPersons = persons.sorted { $0.value > $1.value }

print(sortedPersons)