Home Swift UNIX C Assembly Go Web MCU Research Non-Tech

How to convert an array into a dictionary in Swift

2023-04-22 | Swift | #Words: 570 | 中文原版

Sometimes you need to convert array subscripts and elements into a dictionary. For example, if you use array elements to search for subscripts, if you use a function to search, you have to perform a loop search and acquisition every time, which requires a lot of computing performance and memory. At this time, convert the original array into a dictionary, keyword For array elements, it would be more convenient if the value is a subscript serial number, so that the serial number can be easily found through the value of the element, and there is no need to perform a loop search every time.

To convert an array into a dictionary, you need to obtain each element of the array and its corresponding subscript number. Of course, this function can also be achieved using a For loop, because the subscript serial number is obtained by using i in the For loop through i=0 and i += 1. However, Swift does not have a C-style For loop. The For-In loop used by Swift cannot directly obtain the element subscript number. You need to use Swift’s string enumeration function String.enumerate(), or use a While loop. It can also be done.

The two methods are introduced below. The arrays used are as follows:

let str = ["a", "b", "c"]

How to use a For-In loop:

//Declare to initialize a blank dictionary, the keywords are strings and the values are integers.
var dist = [String: Int]()

// str.enumerated() can obtain the index and value of str at the same time. The names of these two values ​​can be defined by yourself. For the sake of explanation, they are written as index and value here.
for (index, value) in str.enumerated() {
     dist[value] = index
}

How to use While Loop:

//Declare to initialize a blank dictionary, the keywords are strings and the values are integers.
var dist = [String: Int]()

var i = 0
while (i < str.count) {
     dist[str[i]] = i
     i += 1
}

The output of both is:

["c": 2, "b": 1, "a": 0]

In this way, we can easily get the serial number of a certain element, such as getting the serial number of the character c:

//The exclamation point is used here because this value does not necessarily exist in the dictionary, or in the original array. If it is directly equal, the value obtained is the optional value 'Optional' type. Use the exclamation mark to force it to be there. Of course, you can use hello'? 'To add what value to return if not
print(dist["c"]!)
2

I hope these will help someone in need~