Swift——How to convert an array into a dictionary (the key is the array element, and the value is the subscript serial number)

Sometimes it is necessary to convert the subscripts and elements of the array into a dictionary. For example, if you use array elements to find subscripts, if you use a function to search, you have to search and obtain them in a loop every time, which requires a lot of computing performance and memory. At this time, convert the original array into a dictionary, the key It is more convenient for the value to be an array element, and the value is the subscript serial number, so that the serial number can be easily searched by 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 serial number in turn. Of course, this function can also be realized by using a For loop, because the subscript serial number is obtained by ipassing i=0and i += 1obtaining in the For loop. However, Swift does not have a C-style For loop. The For-In loop used by Swift cannot be directly used to obtain the subscript number of an element. You need to use Swift's string enumeration function, or use a While loop String.enumerate().

The following two methods are introduced separately, and the arrays used are as follows:

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

Method using For-In loop:

//声明初始化一个空白字典,关键字为字符串,值为整数
var dist = [String: Int]()

// str.enumerated() 可以同时获取 str的index和value,这两个值的名称可以自己定义,这里为了说明所以写成index和value
for (index, value) in str.enumerated() {
    
    
    dist[value] = index
}

Ways to use a While Loop:

//声明初始化一个空白字典,关键字为字符串,值为整数
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 obtain the serial number of an element, such as the serial cnumber of a character:

//这里使用感叹号是因为这个值不一定存在于字典,或者说原数组中,直接等于的话,得到的是可选值‘Optional’类型,使用感叹号强制为一定有,当然你可以使用问好‘?’来添加如果没有返回什么值
print(dist["c"]!)
2

Hope to help those in need~

Guess you like

Origin blog.csdn.net/qq_33919450/article/details/130299814