LoginSignup
0
1

More than 1 year has passed since last update.

SwiftのDictionaryについて

Posted at

Dictionary(辞書)の基本

Swiftの Dictionary(辞書)は、「順序をもっておらず、キー(Key)と値(Value)が1セットになった複数のデータの集まり」です。

作成したキーは辞書の索引のようなイメージで、
キーを指定して、値の追加や削除、また取得することができます。
→ そのため、同じ名前のキーが複数存在すると混乱が起こってしまうので、辞書のキーは一意的ものである必要があります。

Dictionaryの作り方

var dict1:[String: Int] = [:]
var dict2 = [String: Int]()
var dict3: Dictionary<String, Int> = [:]
var dict4 = Dictionary<String, Int>()

公式ドキュメントでは1と2行目の[Key:Value]de
表記することを推奨しています。

さらに、型推論も使用できるので、データ型の省略もできます。

var dict = ["Key1": 10, "Key2": 5, "Key3": 7, "Key4": 10]

⚠︎値のデータ型がキーごとに違うような場合は、作る際に型の省略はできません。

var student:[String : Any] = ["Name": "Tanaka", "Age": 17, "Gender": "M"]

Dictionary(辞書)の値を取得する

Dictionaryのキーに対応している値を取得するには
[ ] を使ってキーを指定します。

let dict = ["a": 1,"b": 2,"c": 3]
print(dict["a"] ?? "Not Found")  //1

Dictionary(辞書)の値を変更する

Dictionaryの値を変更するには、角括弧[ ]を使ってキーを指定し、そこに新しい値を代入します。

var dict = ["Key1": "orange", "Key2": "peach", "Key3": "banana"]
print(dict)

dict["Key1"] = "grape"
print(dict) 

結果は
["Key1": "orange", "Key2": "peach", "Key3": "banana"]
["Key1": "grape", "Key2": "peach", "Key3": "banana"]
となります。

Dictionaryにキーと値のペアを追加する

Dictionary(辞書)にキーと値のペアを追加するには、[ ]を使って新しいキーを指定して値を代入します。

var dict: [String: Int] = [:]
print(dict)

dict["Key1"] = 1
print(dict)

dict["Key2"] = 2
print(dict)

結果は
[:]
["Key1": 1]
["Key1": 1, "Key2": 2]
となります。

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