Swift Dictionary

Swift dictionaries are used to store unordered collections of data of the same type. Swift dictionaries enforce type checking on elements, and an error will occur if the types are different.

In a Swift dictionary, each value is associated with a unique key, and the key serves as an identifier for that value's data in the dictionary.

Unlike data items in an array, data items in a dictionary have no specific order. We use a dictionary when we need to access data through an identifier (key). This approach is largely similar to how we use a dictionary in the real world to look up word meanings.

Swift dictionary keys have no type restriction and can be integers or strings, but they must be unique.

If you create a dictionary and assign it to a variable, the dictionary will be mutable. This means that after creating the dictionary, you can change its items by adding, removing, or modifying. If you assign a dictionary to a constant, the dictionary is immutable, and both its size and contents cannot be modified.


Creating a Dictionary

We can use the following syntax to create an empty dictionary of a specific type:

var someDict =  [KeyType: ValueType]()

The following is a simple syntax for creating an empty dictionary with keys of type Int and values of type String:

var someDict = [Int: String]()

The following is an example of creating a dictionary:

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

Accessing a Dictionary

We can access dictionary elements using the dictionary's index, with the syntax as follows:

var someVar = someDict[key]

We can learn how to create, initialize, and access a dictionary through the following example:

import Cocoa

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

var someVar = someDict[1]

print( "key = 1 的值为 \(someVar)" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )

The output of the above program execution is:

key = 1 的值为 Optional("One")
key = 2 的值为 Optional("Two")
key = 3 的值为 Optional("Three")

Modifying a Dictionary

We can useupdateValue(forKey:)to add or update the contents of a dictionary. If the key does not exist, the value is added; if it exists, the value corresponding to the key is modified. The updateValue(_:forKey:) method returns an Optional value. An example is as follows:

import Cocoa

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

var oldVal = someDict.updateValue("One 新的值", forKey: 1)

var someVar = someDict[1]

print( "key = 1 旧的值 \(oldVal)" )
print( "key = 1 的值为 \(someVar)" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )

The output of the above program execution is:

key = 1 旧的值 Optional("One")
key = 1 的值为 Optional("One 新的值")
key = 2 的值为 Optional("Two")
key = 3 的值为 Optional("Three")

You can also modify the value in a dictionary using a specified key, as shown below:

import Cocoa

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

var oldVal = someDict[1]
someDict[1] = "One 新的值"
var someVar = someDict[1]

print( "key = 1 旧的值 \(oldVal)" )
print( "key = 1 的值为 \(someVar)" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )

The output of the above program execution is:

key = 1 旧的值 Optional("One")
key = 1 的值为 Optional("One 新的值")
key = 2 的值为 Optional("Two")
key = 3 的值为 Optional("Three")

Removing Key-Value Pairs

We can useremoveValueForKey()method to remove a key-value pair from a dictionary. If the key exists, the method returns the removed value; if not, it returns nil. An example is as follows:

import Cocoa

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

var removedValue = someDict.removeValue(forKey: 2)

print( "key = 1 的值为 \(someDict[1])" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )

The output of the above program execution is:

key = 1 的值为 Optional("One")
key = 2 的值为 nil
key = 3 的值为 Optional("Three")

You can also remove a key-value pair by setting the value of the specified key to nil. An example is as follows:

import Cocoa

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

someDict[2] = nil

print( "key = 1 的值为 \(someDict[1])" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )

The output of the above program execution is:

key = 1 的值为 Optional("One")
key = 2 的值为 nil
key = 3 的值为 Optional("Three")

Iterating Over a Dictionary

We can usefor-inloop to iterate over the key-value pairs in a dictionary. An example is as follows:

import Cocoa

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

for (key, value) in someDict {
   print("字典 key \(key) -  字典 value \(value)")
}

The output of the above program execution is:

字典 key 2 -  字典 value Two
字典 key 3 -  字典 value Three
字典 key 1 -  字典 value One

We can also use the enumerate() method to iterate over a dictionary, which returns the dictionary's index along with (key, value) pairs. An example is as follows:

import Cocoa

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

for (key, value) in someDict.enumerated() {
    print("字典 key \(key) -  字典 (key, value) 对 \(value)")
}

The output of the above program execution is:

字典 key 0 -  字典 (key, value) 对 (2, "Two")
字典 key 1 -  字典 (key, value) 对 (3, "Three")
字典 key 2 -  字典 (key, value) 对 (1, "One")

Converting a Dictionary to an Array

You can extract the key-value pairs of a dictionary and convert them into separate arrays. An example is as follows:

import Cocoa

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)

print("输出字典的键(key)")

for (key) in dictKeys {
    print("\(key)")
}

print("输出字典的值(value)")

for (value) in dictValues {
    print("\(value)")
}

The output of the above program execution is:

输出字典的键(key)
2
3
1
输出字典的值(value)
Two
Three
One

The count Property

We can use the read-onlycountproperty to count how many key-value pairs the dictionary has:

import Cocoa

var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]

print("someDict1 含有 \(someDict1.count) 个键值对")
print("someDict2 含有 \(someDict2.count) 个键值对")

The output of the above program execution is:

someDict1 含有 3 个键值对
someDict2 含有 2 个键值对

The isEmpty Property

We can use the read-only propertyisEmptyto determine whether the dictionary is empty, returning a Boolean value:

import Cocoa

var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
var someDict3:[Int:String] = [Int:String]()

print("someDict1 = \(someDict1.isEmpty)")
print("someDict2 = \(someDict2.isEmpty)")
print("someDict3 = \(someDict3.isEmpty)")

The output of the above program execution is:

someDict1 = false
someDict2 = false
someDict3 = true
Other Extensions