34
31

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 5 years have passed since last update.

配列から重複要素を削除する

Last updated at Posted at 2015-12-10
  • Swift 3 に対応しました
  • reduce を使った場合も掲載しました。

配列中の重複要素を除く方法を。

いわゆる、Rubyとかでいう、uniqueの動作になります。
例) [1, 2, 3, 2, 1, 1, 1, 4] => [1, 2, 3, 4]

実装

// Swift2の頃の記事で書いていた方法
extension Array where Element: Equatable {
    var unique: [Element] {
        var r = [Element]()
        for i in self {
            r += !r.contains(i) ? [i] : []
        }
        return r
    }
}

// reduceを用いて取り除いた場合
extension Array where Element: Equatable {
    var unique: [Element] {
        return reduce([]) { $0.0.contains($0.1) ? $0.0 : $0.0 + [$0.1] }
    }
}

(以前の記事ではArrayのもつElementがHashableに適合しているか見ていましたが、Equatableでも問題ないようなのでそちらにしています)

使ってみる

Sample
let array1 = [5,8,1,2,5,2,7,8,3,5,7,3,4,9,2,1]
print(array1) // [5, 8, 1, 2, 5, 2, 7, 8, 3, 5, 7, 3, 4, 9, 2, 1]
print(array1.unique) // [5, 8, 1, 2, 7, 3, 4, 9]

let array2 = ["a","c","a","b","e","d","c"]
print(array2) // ["a", "c", "a", "b", "e", "d", "c"]
print(array2.unique) // ["a", "c", "b", "e", "d"]

// Enumも試してみる
enum SomeType{
    case A,B,C,D,E
}
var array3 = [SomeType.A,.C,.B,.D,.A,.C,.B]
print(array3) // [SomeType.A, SomeType.C, SomeType.B, SomeType.D, SomeType.A, SomeType.C, SomeType.B]
print(array3.unique) // [SomeType.A, SomeType.C, SomeType.B, SomeType.D]
34
31
1

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
34
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?