符合要求
Student
到
Hashable
并实施
==
和
hash(into:)
方法,
struct Student: Hashable {
var name: String
var contact: String
var twitter: String
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(contact)
hasher.combine(twitter)
}
static func == (lhs: Student, rhs: Student) -> Bool {
return lhs.name == rhs.name && lhs.contact == rhs.contact && lhs.twitter == rhs.twitter
}
}
现在,您可以对副本进行分组
学生
实例使用
Dictionary's
init(grouping:by:)
,即。
var students = [Student(name: "Alex", contact: "1234", twitter: "XYZ"), Student(name: "Alex", contact: "1234", twitter: "XYZ"), Student(name: "Mike", contact: "98765", twitter: "XYZ"), Student(name: "Mike", contact: "09876", twitter: "PQR")]
let dict = Dictionary(grouping: students, by: { $0.hashValue })
接下来,拿到
students
从
dict
使用
compactMap(_:)
像这样,
students = dict.compactMap({
var countText = ""
if $0.value.count > 1 {
countText = " x\( $0.value.count)"
}
var student = $0.value.first
student?.name += countText
return student
})
最后,使用
学生
作为你的
tableView's
dataSource
.