使用日期组件来设置唯一性,因此忽略时间部分
struct Record {
let date: Date
let name: String
}
let now = Date()
let soon = Date(timeIntervalSinceNow: 100)
let future = Calendar.current.date(byAdding: .day, value: 1, to: now)!
let records = [Record(date: now, name: "Now"),
Record(date: soon, name: "Soon"), // same day so should be removed
Record(date: future, name: "Future")]
var unique = Set<DateComponents>()
let result = records.filter {
let comps = Calendar.current.dateComponents([.day, .month, .year], from: $0.date)
if unique.contains(comps) {
return false
}
unique.insert(comps)
return true
}
print(result)
// [Record(date: 2018-10-11 13:47:17 +0000, name: "Now"),
// Record(date: 2018-10-12 13:47:17 +0000, name: "Future")]