4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Swift] 配列から特定のプロパティの重複を削除する方法

Posted at

配列から特定のプロパティの値が重複している要素を削除したい時があったので備忘録として残します。

実装

public extension Sequence where Element: Equatable {
    func removeDuplicates<T: Hashable>(keyPath: KeyPath<Element, T>) -> [Element] {
        var seen = Set<T>()
        return filter { (element) -> Bool in
            guard !seen.contains(element[keyPath: keyPath]) else { 
                return false 
            }
            seen.insert(element[keyPath: keyPath])
            return true
        }
    }
}

重複を削除したい対象のプロパティのKeyPathを引数に指定できます。

使用方法

struct Person {
    let id: Int
    let name: String
}

let people = [
    Person(id: 1, name: "John"),
    Person(id: 2, name: "Doe"),
    Person(id: 1, name: "John")
]

peopleにはidが重複している要素が含まれているので、これを削除してみます。

let uniquePeople = people.removeDuplicates(keyPath: \.id)
print(uniquePeople)  
// 出力: [Person(id: 1, name: "John"), Person(id: 2, name: "Doe")]

このコードを実行すると、このようにidプロパティが重複している要素が削除されます。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?