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?

Swift Dictionaryの基本と応用

Posted at

はじめに

Swift の Dictionary は、キーと値のペアを保存できる便利なデータ構造です。しかし、Swift初心者にとっては少し理解しづらい部分もあります。


1. Dictionaryとは?

Dictionaryキー(Key)と値(Value)をペアで管理するコレクション型 です。キーを使って値にアクセスできるため、リストや配列よりもデータの検索が高速です。

基本の構文:

var dictionary: Dictionary<String, Int> = Dictionary<String, Int>() // 空の辞書を作成

Swift では、型推論を活用して次のように簡潔に書くこともできます。

var dictionary = ["apple": 100, "banana": 150, "cherry": 200] // 初期値を持つ辞書

この辞書には、果物の名前(String)をキーとして、価格(Int)を値として保存しています。

また、空の辞書の作成の際に、次のように書くこともできます。

var emptyDictionary1: [String: Int] = [:]  // 空の辞書
var emptyDictionary2 = Dictionary<String, Int>() // 空の辞書

2. Dictionaryの基本操作

2.1 値の取得

辞書から値を取得するには、キーを指定します。

let price = dictionary["apple"] // 100

しかし、キーが存在しない場合は nil になるため、安全に扱うにはオプショナルバインディングを使います。

if let price = dictionary["mango"] {
    print("価格は \(price) 円です")
} else {
    print("その商品はありません")
}

2.2 値の追加・更新

辞書に値を追加するには、新しいキーと値を代入します。

dictionary["mango"] = 180 // 追加

既存のキーに対して代入すると、値が更新されます。

dictionary["banana"] = 160 // 更新(150 → 160)

2.3 値の削除

辞書から値を削除するには removeValue(forKey:) を使います。

dictionary.removeValue(forKey: "cherry") // "cherry" を削除

または nil を代入する方法でも削除できます。

dictionary["banana"] = nil // "banana" を削除

3. Dictionaryの応用

3.1 ループ処理

辞書の全データを取得するには for-in ループを使います。

for (key, value) in dictionary {
    print("\(key) の価格は \(value) 円です")
}

3.2 キーや値の一覧を取得

let keys = Array(dictionary.keys)   // ["apple", "banana", "mango"]
let values = Array(dictionary.values) // [100, 160, 180]

3.3 型エイリアス(typealias)を活用する

Swift では typealias を使って Dictionary の型を簡潔にできます。

typealias FruitPriceList = Dictionary<String, Int>
var fruitPrices: FruitPriceList = ["apple": 100, "banana": 150]

空の辞書の作成の際にも以下のように書けます。

typealias FruitPriceList = Dictionary<String, Int>
var fruitPrices2 = FruitPriceList()  // 空の辞書
var fruitPrices3: FruitPriceList = [:]  // 空の辞書

3.4 ネストした辞書(辞書の中に辞書)

var users = [
    "user1": ["name": "Alice", "age": "25"],
    "user2": ["name": "Bob", "age": "30"]
]

if let user1Name = users["user1"]?["name"] {
    print("User1 の名前は \(user1Name) です")
}

まとめ

Swift の Dictionary は、キーと値を効率よく管理できる強力なデータ構造です。

Dictionary はキーと値のペアを管理するコレクション
✅ 値の追加、取得、更新、削除が簡単にできる
for-in ループで全データを取得可能
typealias を使うとコードがスッキリする
✅ ネストした辞書を使うことでデータの構造化が可能

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?