Swift 中的字典迭代
我們可以使用多種方法在 Swift 中迭代字典。您也可以迭代字典的鍵和值。
我們將使用以下不同的方法來迭代字典:
使用 for-in 迴圈
迭代字典中的所有鍵
迭代字典中的所有值
使用 enumerated() 方法迭代所有元素
使用 for-in 迴圈
大多數情況下,我們使用 for-in 迴圈來迭代字典。使用 for-in 迴圈,您可以像下面這樣迭代字典的所有元素:
語法
for (key, value) in dictionary { }
在語法中,key 和 value 是將分別儲存當前鍵和值的變數的名稱。
示例
import Foundation let colorsDictionary = [ "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "aqua": "#00ffff", "aquamarine": "#7fffd4", "azure": "#f0ffff", "beige": "#f5f5dc", "bisque": "#ffe4c4", "black": "#000000", "blanchedalmond": "#ffebcd", "blue": "#0000ff", "blueviolet": "#8a2be2", "brown": "#a52a2a" ] for (colorName, colorValue) in colorsDictionary { print("Name: \(colorName) and its hex code: \(colorValue)") }
輸出
Name: brown and its hex code: #a52a2a Name: bisque and its hex code: #ffe4c4 Name: blueviolet and its hex code: #8a2be2 Name: aqua and its hex code: #00ffff Name: aliceblue and its hex code: #f0f8ff Name: aquamarine and its hex code: #7fffd4 Name: azure and its hex code: #f0ffff Name: beige and its hex code: #f5f5dc Name: blanchedalmond and its hex code: #ffebcd Name: blue and its hex code: #0000ff Name: antiquewhite and its hex code: #faebd7 Name: black and its hex code: #000000
在上面的示例中,我們建立了一個字典來定義一些顏色及其名稱和十六進位制值。使用 for-in 迴圈,逐個迭代所有元素,順序未指定。它以 (鍵, 值) 對的形式給出元素。
迭代所有鍵
如果您想一次訪問或迭代所有鍵,可以使用“keys”屬性。此屬性返回一個字串型別的陣列,其中包含字典的所有鍵。
示例
import Foundation let colorsDictionary = ["aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "aqua": "#00ffff", "aquamarine": "#7fffd4", "azure": "#f0ffff", "beige": "#f5f5dc", "bisque": "#ffe4c4", "black": "#000000", "blanchedalmond": "#ffebcd", "blue": "#0000ff", "blueviolet": "#8a2be2", "brown": "#a52a2a" ] for key in colorsDictionary.keys { print("Key: \(key)") }
輸出
Key: brown Key: antiquewhite Key: bisque Key: beige Key: black Key: aqua Key: azure Key: aliceblue Key: blue Key: blueviolet Key: aquamarine Key: blanchedalmond
在上面的示例中,我們建立了一個字典來定義一些顏色及其名稱和十六進位制值。使用 for-in 迴圈迭代字典的所有鍵。
迭代所有值
如果您想一次訪問或迭代所有值,可以使用“values”屬性。此屬性返回一個字串型別的陣列,其中包含字典的所有值。
示例
import Foundation let colorsDictionary = ["aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "aqua": "#00ffff", "aquamarine": "#7fffd4", "azure": "#f0ffff", "beige": "#f5f5dc", "bisque": "#ffe4c4", "black": "#000000", "blanchedalmond": "#ffebcd", "blue": "#0000ff", "blueviolet": "#8a2be2", "brown": "#a52a2a" ] for value in colorsDictionary.values { print("Value: \(value)") }
輸出
Value: #00ffff Value: #f0f8ff Value: #f5f5dc Value: #000000 Value: #f0ffff Value: #ffebcd Value: #7fffd4 Value: #ffe4c4 Value: #0000ff Value: #faebd7 Value: #a52a2a Value: #8a2be2
結論
我們可以迭代 Swift 中字典的元素、鍵和值。字典提供“keys”屬性來訪問所有鍵的陣列。同樣,“values”屬性提供所有值的陣列。
您可以使用 for-in 迴圈和其他方法迭代字典。但請記住,元素的順序未指定。但是,使用 enumerated() 函式,您仍然可以在訪問元素時跟蹤其索引。
廣告