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.

Swift key valueで配列要素の追加、変更をしたい

Last updated at Posted at 2023-01-26

Swiftで辞書型で[String: [String,Int]]のようなとき後から要素追加、変更方法を書きました。
他言語の連想配列的な処理をしたい。
例文はChatGPTで生成しました。

対象読者

swift初学者

Dictionaryで特定のキーに対応する値を追加したい場合

keyとvalueの新規追加
var dict: [String: [(String,Int)]] = [:]
// var dict = [String: [(String,Int)]]() これも同じ
dict["key"] = [("value1",1)]

この例では、新しい要素として、キー "key"、値 [("value1", 1)] が追加されています。

すでに存在するキーに値を追加したい場合

value配列に値を追加
dict["key"]?.append(("value2",2))
// dict["key"]? += [("value2",2)] これでも同じ

値 ("value2",2)が追加される。

特定のインデックスの値を変更したい場合

value配列のindex値を変更
dict["key"]?[0] = ("newValue1",1)
// [0]でindexを指定

このように書けば、値 ("newValue1",1)が変更される。

上記の例では、dict["key"]がnilの場合にクラッシュしないように、Optional chainingを使用しています。

上記を出力すると

var dict: [String: [(String,Int)]] = [:]
dict["key"] = [("value1",1)]
dict["key"]?.append(("value2",2))
dict["key"]?[0] = ("newValue1",1)

print(dict) // ["key": [("newValue1", 1), ("value2", 2)]]
print(dict["key"]?[0]) // Optional(("newValue1", 1))
print(dict["key"]![0]) // ("newValue1", 1)

for value in dict["key"]!{
    print("\(value.0) \(value.1)") // newValue1 1
}                                  // value2 2

おわりに

今回詰まったのはdict["key"]?の"?"をつける部分

dict["key"]がnilの場合にクラッシュしないように、Optional chainingを使用しています

書き方がわからず苦戦しました。
今読み返すと公式ソースにも?付いてる部分ありました。

参考

公式Apple/swift/dictionary
コード検証:paiza.io

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