0
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.

タカシAdvent Calendar 2022

Day 18

【Swift】配列の要素を追加・削除する

Posted at

配列の要素を追加

配列の要素を追加したい場合はappendを使用する。

配列.append(値)

引数には追加する値を記述する。

var characters: [String] = ["ロイド", "ヨル", "アーニャ", "ボンド", "ダミアン"]
print(characters) //["ロイド", "ヨル", "アーニャ", "ボンド", "ダミアン"]

characters.append("ベッキー"); // ここで要素を1つ追加
print(characters) //["ロイド", "ヨル", "アーニャ", "ボンド", "ダミアン", "ベッキー"]

+=演算子を使用して配列の要素を1つ追加することも可能。

var characters: [String] = ["ロイド", "ヨル", "アーニャ", "ボンド", "ダミアン"]
print(characters) //["ロイド", "ヨル", "アーニャ", "ボンド", "ダミアン"]

characters += ["フランキー"]; // +=演算子を使用して要素を1つ追加
print(characters) //["ロイド", "ヨル", "アーニャ", "ボンド", "ダミアン", "フランキー"]

追加する場所を指定して要素を追加する場合はinsertを使用する。

var numbers: [Int] = [1, 2, 3, 4, 5,]
numbers.insert(100, at: 2)
print(numbers) //[1, 2, 100, 3, 4, 5]

配列の要素を削除

配列の要素を削除するときはremoveを使用する。

var characters: [String] = ["ロイド", "ヨル", "アーニャ", "ボンド", "ダミアン"]
characters.remove(at: 3)
print(characters) //["ロイド", "ヨル", "アーニャ", "ダミアン"]

全てを削除する場合はremoveAll()を使用する。

var couple: [String] = ["デート", "クリスマス", "プレゼント", "サンタクロース", "トナカイ"]
couple.removeAll()
print(couple) //[]

メリークリスマス。

0
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
0
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?