Swift dictionary


Release date:2023-11-30 Update date:2023-12-11 Editor:admin View counts:151

Label:

Swift dictionary

Swift dictionaries are used to store unordered collections of data of the same type. Swift dictionaries force the type of elements to be detected and will report errors if the types are different.

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

Unlike the data items in the array, the data items in the dictionary do not have a specific order. We use dictionaries when we need to access data through identifiers (keys), much the same way we use dictionaries to look upthe meaning of words in the real world.

Swift dictionary key there are no type restrictions that can be integers or strings, but must be unique.

If you create a dictionary and assign a value to a variable, the dictionary created can be modified. This means that after creating a dictionary, you can change the items in the dictionary by adding, deleting, and modifying. If you assign a dictionary to a constant, the dictionary cannot be modified,and neither the size nor the 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]()

The following is to create an empty dictionary with a key of type Int the type of the value is String the simple syntax of:

var someDict = [Int: String]()

The following is an example of creating a dictionary:

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

Access dictionary

We can access the elements of the array according to the index of the dictionary. The syntax is as follows:

var someVar = someDict[key]

We can learn how to create, initialize, and access dictionaries through the following examples:

import Cocoa

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

var someVar = someDict[1]

print( "key = 1 value is \(someVar)" )
print( "key = 2 value is \(someDict[2])" )
print( "key = 3 value is \(someDict[3])" )

The output of the above program execution is as follows:

key = 1 value is Optional("One")
key = 2 value is Optional("Two")
key = 3 value is Optional("Three")

Modify the dictionary

We can use updateValue(forKey:) add or update the contents of the dictionary. If key does not exist, add a value, and modify if it exists key the corresponding value. updateValue(_:forKey:) method returns Optional value. Examples are as follows:

import Cocoa

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

var oldVal = someDict.updateValue("One new value", forKey: 1)

var someVar = someDict[1]

print( "key = 1 old value \(oldVal)" )
print( "key = 1 value is \(someVar)" )
print( "key = 2 value is \(someDict[2])" )
print( "key = 3 value is \(someDict[3])" )

The output of the above program execution is as follows:

key = 1 old value Optional("One")
key = 1 value is Optional("One new value")
key = 2 value is Optional("Two")
key = 3 value is Optional("Three")

You can also use the specified key to modify the value of the dictionary, as follows:

import Cocoa

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

var oldVal = someDict[1]
someDict[1] = "One new value"
var someVar = someDict[1]

print( "key = 1 old value \(oldVal)" )
print( "key = 1 value is \(someVar)" )
print( "key = 2 value is \(someDict[2])" )
print( "key = 3 value is \(someDict[3])" )

The output of the above program execution is as follows:

key = 1 old value Optional("One")
key = 1 value is Optional("One new value")
key = 2 value is Optional("Two")
key = 3 value is Optional("Three")

Remove Key-Value pair

We can use it. removeValueForKey() method to remove the dictionary key-value . If key the value that the method returns removed exists, if it does not exist. nil . Examples are as follows:

import Cocoa

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

var removedValue = someDict.removeValue(forKey: 2)

print( "key = 1 old value \(someDict[1])" )
print( "key = 2 value is \(someDict[2])" )
print( "key = 3 value is \(someDict[3])" )

The output of the above program execution is as follows:

key = 1 value is Optional("One")
key = 2 value is nil
key = 3 value is Optional("Three")

You can also specify the value of the key as nil to remove key-value right. Examples are as follows:

import Cocoa

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

someDict[2] = nil

print( "key = 1 value is \(someDict[1])" )
print( "key = 2 value is \(someDict[2])" )
print( "key = 3 value is \(someDict[3])" )

The output of the above program execution is as follows:

key = 1 value is Optional("One")
key = 2 value is nil
key = 3 value is Optional("Three")

Ergodic dictionary

We can use it. for-in loop to traverse the key-value pairs in a dictionary. Examples are as follows:

import Cocoa

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

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

The output of the above program execution is as follows:

dictionary key 2 -  dictionary value Two
dictionary key 3 -  dictionary value Three
dictionary key 1 -  dictionary value One

We can also use it. enumerate() method to traverse the dictionary, returning the index of the dictionary and (key,value) , the example is as follows:

import Cocoa

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

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

The output of the above program execution is as follows:

dictionary key 0 -  dictionary (key, value) for (2, "Two")
dictionary key 1 -  dictionary (key, value) for (3, "Three")
dictionary key 2 -  dictionary (key, value) for (1, "One")

Convert dictionaries to arrays

You can extract key-value pairs of dictionaries and convert them to separatearrays. Examples are 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("Output dictionary key(key)")

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

print("Output dictionary values(value)")

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

The output of the above program execution is as follows:

Output dictionary key(key)
2
3
1
Output dictionary values(value)
Two
Three
One

count attribute

We can use 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 contains \(someDict1.count) key value pairs")
print("someDict2 contains \(someDict2.count) key value pairs")

The output of the above program execution is as follows:

someDict1 contains 3 key value pairs
someDict2 contains 2 key value pairs

isEmpty Attribute

Y we can use the read-only attribute isEmpty to determine whether the dictionary is empty, return 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 as follows:

someDict1 = false
someDict2 = false
someDict3 = true

Powered by TorCMS (https://github.com/bukun/TorCMS).