Swiftで配列の重複を取り除く方法です。
structの特定の値をkeyとして取り除く方法を今回はご紹介します。
extension Array {
func unique<T>(by keyPath: KeyPath<Element, T>) -> Array where T: Hashable {
var dictionary: [T: Element] = [:]
forEach { value in
dictionary[value[keyPath: keyPath]] = value
}
return dictionary.map(\.value)
}
}
使い方
struct Item {
var title: String
var value: Int
}
let items = [
Item(title: "a", value: 1),
Item(title: "b", value: 2),
Item(title: "b", value: 3),
Item(title: "c", value: 4),
]
/*
Result
[
Item(title: "a", value: 1),
Item(title: "b", value: 3),
Item(title: "c", value: 4),
]
*/
let filteredItems = items.unique(by: \.title)