Dictionaries help you store pairs of related information, like names and phone numbers. You can quickly find a value by using its key.
0
0
Dictionary creation and access in Swift
Introduction
When you want to store a list of items with labels, like a phone book.
When you need to look up information fast using a unique key.
When you want to group related data together, like a person's details.
When you want to update or add new information easily by key.
Syntax
Swift
var dictionaryName: [KeyType: ValueType] = [key1: value1, key2: value2] // Access value by key let value = dictionaryName[key]
Keys must be unique and hashable (like strings or numbers).
Accessing a key returns an optional value because the key might not exist.
Examples
This creates a dictionary with names as keys and ages as values. Then it gets Alice's age.
Swift
var ages: [String: Int] = ["Alice": 30, "Bob": 25] let aliceAge = ages["Alice"]
Swift can infer the types. This dictionary stores countries and their capitals.
Swift
var capitals = ["France": "Paris", "Japan": "Tokyo"] let capitalOfJapan = capitals["Japan"]
This creates an empty dictionary and adds a key-value pair later.
Swift
var emptyDict = [String: String]() emptyDict["key"] = "value"
Sample Program
This program creates a dictionary of fruits and their colors. It safely accesses the color of Apple and Orange, showing how to handle missing keys.
Swift
import Foundation var fruitsColors: [String: String] = ["Apple": "Red", "Banana": "Yellow", "Grape": "Purple"] if let appleColor = fruitsColors["Apple"] { print("The color of Apple is \(appleColor).") } else { print("Apple color not found.") } // Trying to access a key that does not exist if let orangeColor = fruitsColors["Orange"] { print("The color of Orange is \(orangeColor).") } else { print("Orange color not found.") }
OutputSuccess
Important Notes
Always use optional binding (if let) when accessing dictionary values to avoid errors if the key is missing.
You can add or update values by assigning to a key, like dict["newKey"] = newValue.
Dictionaries do not keep order, so the order of items is not guaranteed.
Summary
Dictionaries store data in key-value pairs for quick lookup.
Use square brackets with a key to get or set values.
Accessing a key returns an optional, so handle missing keys safely.