Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. Dictionary Basics / .keys / .values

Dictionary Basics / .keys / .values

A Swift dictionary (Dictionary) is a collection that stores key-value pairs. Keys are unique, and the order of elements is not guaranteed.

Syntax

// Declaring and initializing a dictionary
var dict: [String: Int] = ["apple": 100, "banana": 200]
var emptyDict = [String: Int]()          // Empty dictionary
var emptyDict2: [String: Int] = [:]     // Empty dictionary (alternative syntax)

// Accessing an element (returns an Optional)
let value = dict["apple"]               // Optional(100)

// Listing keys and values
let keys = dict.keys                    // Keys view
let values = dict.values                // Values view

Properties and Methods

Property / MethodDescription
dict[key]Returns the value for the specified key as an Optional.
dict.countReturns the number of key-value pairs in the dictionary.
dict.isEmptyReturns a Bool indicating whether the dictionary is empty.
dict.keysReturns all keys in the dictionary.
dict.valuesReturns all values in the dictionary.
dict[key] = valueSets a value for the given key. Assigning nil removes the key.

Sample Code

// Creating a dictionary and performing basic operations
var prices: [String: Int] = ["apple": 100, "banana": 200, "cherry": 300]

// Retrieving a value (Optional)
if let price = prices["apple"] {
    print("Price of apple: \(price)")
}

// Using a default value when the key does not exist
let grapePrice = prices["grape", default: 0]
print("Price of grape: \(grapePrice)")

// Adding and updating values
prices["grape"] = 400
prices["apple"] = 120

// Iterating over key-value pairs
for (fruit, price) in prices {
    print("\(fruit): \(price)")
}

// Displaying keys in sorted order
let sortedKeys = prices.keys.sorted()
print("Keys: \(sortedKeys)")

// Dictionary information
print("Count: \(prices.count)")
print("Is empty: \(prices.isEmpty)")

// Checking if a key exists
if prices.keys.contains("banana") {
    print("banana exists")
}

Overview

Swift dictionaries are declared with the type [Key: Value]. Accessing an element returns an Optional, so accessing a key that does not exist is safe and will not cause a crash.

You can use subscript access with a default value (dict[key, default: value]) to safely retrieve a value even when the key is absent. Because dictionaries do not guarantee key order, the iteration order when using for-in may differ each time.

For updating and deleting dictionary entries, see dict.updateValue() / Removing entries / mapValues().

If you find any errors or copyright issues, please .