請原諒下面的人為示例,但是我該如何過濾呢?使用Set重復資料洗掉不是一種選擇,因為我的真實資料物件具有另一個對每個物件都是唯一的屬性。
struct MyDataObject {
var startDate: Date
var endDate: Date
}
let dataObject1 = MyDataObject(startDate: Date().startOfDay(), endDate: Date().startOfDay())
let duplicateDataObject = MyDataObject(startDate: Date().startOfDay(), endDate: Date().startOfDay())
let array = [dataObject1, duplicateDataObject]
//How to filter to end up with an array of data objects with a unique start date?
uj5u.com熱心網友回復:
https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md
import Algorithms
array.uniqued(on: \.startDate)
或者,如果您需要更多地控制選擇哪些元素:
array.uniqued(on: \.startDate) { [$0, $1].max(by: \.endDate)! }
import struct OrderedCollections.OrderedDictionary
public extension Sequence {
@inlinable func uniqued<Subject: Hashable>(
on projection: (Element) throws -> Subject,
uniquingWith combine: (Element, Element) throws -> Element
) rethrows -> [Element] {
try OrderedDictionary(keyed(by: projection), uniquingKeysWith: combine)
.values
.elements
}
@inlinable func max<Comparable: Swift.Comparable>(
by getComparable: (Element) throws -> Comparable
) rethrows -> Element? {
try self.max {
try getComparable($0) < getComparable($1)
}
}
}
public extension Sequence {
@inlinable func keyed<Key: Hashable>(
by key: (Element) throws -> Key
) rethrows -> [KeyValuePairs<Key, Element>.Element] {
try map { (try key($0), $0) }
}
}
uj5u.com熱心網友回復:
你的意思是過濾,所以你只保留在原始集合中出現一次的元素?
import OrderedCollections
struct A {
let id: String
let thing: String
}
let things: [A] = [
.init(id: "1", thing: "thing"),
.init(id: "2", thing: "thing"),
.init(id: "3", thing: "thing"),
.init(id: "2", thing: "thing"),
.init(id: "1", thing: "thing"),
.init(id: "4", thing: "thing"),
.init(id: "2", thing: "thing"),
]
let uniqueThings = OrderedDictionary<String, [A]>(grouping: things, by: \.id)
.filter { $0.value.count == 1 }
.values
僅給出具有唯一 id 的 A(在本例中為 3 和 4)
或者你的意思只是去重復,比如https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md uniqued(on:)如果是這樣,如果有多個元素應該保留,第一個看到,最后一個等?
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/480812.html
