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

【Swift】配列に値を追加するときに、重複を避ける方法2選

1
Last updated at Posted at 2023-07-26

はじめに

配列に値を追加するときに、重複を避ける方法を紹介します。

対象者

最近Swiftを学び始めた初心者の方

追記(23/07/27)

もっと良いやり方が見つかったのでそちらを紹介します。

やり方

1. Setを使う

Setには配列によく似たデータ構造です。
しかし、Setは重複を許さないという特徴があります。
この特徴を活かし、配列をSetに変換してから、再度配列に変換することで重複を避けることができます。
ただし、Setは順序を保持しないので、順序を保持したい場合はこの方法は使えません。

var array = [1, 2, 3]
func add(_ value: Int) {
    array = Array(Set(array + [value]))
}
add(1)
print(array)

2. containsを使う

containsは配列に指定した値が含まれているかどうかを判定する関数です。
この関数を使って、配列に指定した値が含まれていない場合のみ、配列に値を追加することで重複を避けることができます。

var array = [1, 2, 3]
func add(_ value: Int) {
    if !array.contains(value) {
        array.append(value)
    }
}
add(1)
print(array)

おわりに

重複させることなく配列に値を追加する方法を紹介しました。この記事が参考になったという方は、いいねとフォローよろしくお願いします。

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?