我有一个如下所示的数组:
var persons = [Person]()
一个人包含这个:
id : Int
name : String
age : Int
gender : String
在我的人员列表中,我有多个人,但如何在唯一名称上对此列表进行排序?
我发现了这个let unique = Array(Set(originals))
,但它似乎不适用于对象列表,我想保留对象的所有信息。
如果我的列表包含以下行:
Adam, Adam, John, John, Michael, Nick, Tony
我只想表明:
Adam, John, Michael, Nick Tony
我仍然希望能够让亚当斯年龄增长。
有什么想法吗?
修改
人员声明
import Foundation
public class Person : NSObject {
var id = ""
var name = ""
var age = 0
var gender = ""
}
func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name
}
答案 0 :(得分:2)
您需要添加此扩展程序以从人员阵列返回有序集。
extension Collection where Element: Hashable {
var orderedSet: [Element] {
var set: Set<Element> = []
return reduce(into: []){ set.insert($1).inserted ? $0.append($1) : () }
}
}
您还必须使您的Person类Equatable:
func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.id == rhs.id
}
class Person: Equatable {
let id: String
let name: String
init(id: String, name: String) {
self.id = id
self.name = name
}
}
测试
let person1 = Person(id: "1", name: "Adam")
let person2 = Person(id: "1", name: "Adam")
let person3 = Person(id: "2", name: "John")
let person4 = Person(id: "2", name: "John")
let person5 = Person(id: "3", name: "Michael")
let person6 = Person(id: "4", name: "Nick")
let person7 = Person(id: "5", name: "Tony")
let people = [person1,person2,person3,person4,person5,person6,person7]
people.orderedSet //[{id "1", name "Adam"}, {id "2", name "John"}, {id "3", name "Michael"}, {id "4", name "Nick"}, {id "5", name "Tony"}]