1
1

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

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)
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?