2
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】Firestoreで配列やMap型配列に要素を追加・削除する方法

Last updated at Posted at 2023-04-26

配列への追加・削除

スクリーンショット 2023-04-27 7.38.27.png
usersというコレクションにあるtaroというドキュメントのfavoritesフィールドに要素を追加・削除することを考えます。

let taroRef = db.collection("users").document("taro")
// 追加
taroRef.updateData([
    "favorites": FieldValue.arrayUnion(["焼肉"])
])
// 削除
taroRef.updateData([
    "favorites": FieldValue.arrayRemove(["リンゴ"])
])

Map型配列への追加・削除

スクリーンショット 2023-04-27 7.45.55.png
usersというコレクションにあるjiroというドキュメントのhomeworkフィールドに要素を追加・削除することを考えます。
homeworkフィールドはMap型の配列になっており、それぞれの要素には「科目名」と「優先度」のデータが入っています。
[]の数に注意してください。

let jiroRef = db.collection("users").document("jiro")
// 追加
jiroRef.updateData([
    "homework": FieldValue.arrayUnion([[
        "subject": "社会",
        "priority": 4
    ]])
])
// 削除
jiroRef.updateData([
    "homework": FieldValue.arrayRemove([[
        "subject": "国語",
        "priority": 1
    ]])
])

注意点

この方法では、配列に既に存在する要素と同じ内容のものは追加することができないので注意する必要があります。
上の例だと「カレー」「リンゴ」「ピザ」は既に存在するため、再度追加することはできません。

参考

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