Swift dictionary

Swift dictionaries are used to store a collection of out-of-order data of the same type, and the Swift array enforces detection of the type of element, which is reported as wrong if the type is different.

Each value in the Swift dictionary is associated with a unique key, which acts as an identifier for this value data in the dictionary.

Different from the data items in the array, the data items in the dictionary are not in a specific order. W e use dictionaries when we need access to data through identifiers (keys), much like we do in the real world.

The key of the Swift dictionary has no type restrictions that can be integers or strings, but must be unique.

If you create a dictionary and assign it to a variable, the dictionary you create can be modified. T his means that after you create a dictionary, you can change the items in the dictionary by adding, deleting, and modifying them. If you assign a dictionary to a constant, the dictionary cannot be modified, and neither the size or content of the dictionary can be modified.


Create a dictionary

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

var someDict =  [KeyType: ValueType]()

Here's a simple syntax for creating an empty dictionary with the key type Int and the value type String:

var someDict = [Int: String]()

Here's an example of creating a dictionary:

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

Access the dictionary

We can access the elements of the array based on the dictionary index, as follows:

var someVar = someDict[key]

We can learn how to create, initialize, and access a dictionary by following the following examples:

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")

Modify the dictionary

We can use updateValue (forKey:) to add or update the contents of the dictionary. I f key does not exist, a value is added and, if present, a value corresponding to key is modified. T he updateValue method returns the Optional value. Here's an example:

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 of the dictionary by specifying key, as follows:

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")

Remove the Key-Value pair

We can use the removeValueForKey() method to remove the dictionary key-value pair. I f key exists the method returns the removed value, if it does not return nil. Here's an example:

import Cocoa

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

var removedValue = someDict.removeValueForKey(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 key-value pairs by specifying the value of the key to nil. Here's an example:

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")

Traverse the dictionary

We can use the for-in loop to traverse key-value pairs in a dictionary. Here's an example:

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 for dictionary traversal, returning the dictionary index and (key, value) pairs, as follows:

import Cocoa

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

for (key, value) in someDict.enumerate() {
    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")

The dictionary is converted to an array

You can extract the key-value pair of the dictionary and convert it to a separate array. Here's an example:

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

Count property

We can use the read-only count property to calculate 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 个键值对

IsEmpty property

Y We can tell if the dictionary is empty by the read-only property isEmpty, returning the 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