Swift - 字典



字典用於儲存相同型別值的無序列表。Swift 進行了嚴格的檢查,即使是錯誤的型別,也不會允許您將其新增到字典中。

字典使用一個稱為鍵的唯一識別符號來儲存值,稍後可以透過相同的鍵來引用和查詢該值。與陣列不同,字典中的專案沒有指定的順序。當您需要根據識別符號查詢值時,可以使用字典。在字典中,鍵可以是整數或字串,沒有限制,但必須在字典中唯一。而值可以重複。

如果您將建立的字典賦值給一個變數,那麼它始終是可變的,這意味著您可以透過新增、刪除或更改其專案來更改它。但是,如果您將字典賦值給一個常量,那麼該字典是不可變的,其大小和內容都不能更改。

在 Swift 中建立字典

字典包含鍵值對。鍵值對的型別可以相同也可以不同,這意味著鍵和值的型別不必相同。因此,我們可以使用以下語法建立一個特定型別的字典。

語法

以下是建立字典的語法:

var someDict =  [KeyType: ValueType](key:value)

我們也可以在不指定型別的情況下建立字典。在這種情況下,編譯器將根據賦值的值自動獲取字典的型別。以下是建立字典的語法:

var someArray = [key1: value, key2: value, key3: value3]

在 Swift 中過濾字典元素

為了過濾字典元素,Swift 提供了一個名為 filter() 的預定義函式。filter() 函式將閉包作為引數,並返回一個新的字典,該字典只包含閉包中滿足給定條件的鍵值對。

語法

以下是 filter() 函式的語法:

func filter(closure)

示例

import Foundation

// Defining and initializing a dictionary
var myDict = [3: "Blue", 4: "Pink", 5:"Green", 7:"Pink"]

// Filtering out only pink color using filter() function
let color = myDict.filter { $0.value == "Pink" }

print(color)

輸出

它將產生以下輸出:

[4: "Pink", 7: "Pink"]

在 Swift 中訪問字典

為了訪問給定字典的鍵值對,我們可以使用以下任何一種方法:

使用下標語法

我們可以透過使用下標語法從字典中檢索值,在下標語法中,將要檢索的值的鍵放在字典名稱後面的方括號內。

語法

以下是訪問字典的語法:

var someVar = someDict[key]

示例

import Foundation

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

// Accessing the value of key = 1 using subscript syntax
var someVar = someDict[1]

// Checking if the value is not nil before using it
if let result = someVar  {
   print("Value of key = 1 is \(result)")
} else {
   print("Value not found")
}

輸出

它將產生以下輸出:

Value of key = 1 is One

使用 keys 屬性

我們可以使用 keys 屬性單獨訪問鍵。此屬性將返回字典中存在的全部鍵。

語法

以下是 keys 屬性的語法:

dictionary.keys

示例

import Foundation

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

// Accessing the keys
var output = someDict.keys

print(output)
輸出

它將產生以下輸出:

[1, 2, 3]

使用 values 屬性

我們可以使用 values 屬性單獨訪問值。此屬性將返回字典中存在的全部值。

語法

以下是 values 屬性的語法:

dictionary.values

示例

import Foundation

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

// Accessing the values
var output = someDict.values

print(output)
輸出

它將產生以下輸出:

["Two", "One", "Three"]

在 Swift 中修改字典

為了修改關聯鍵的現有值,Swift 提供了一個名為 updateValue(forKey:) 的預定義方法。如果給定的鍵值對在給定的字典中不存在,則此方法會將該對新增到字典中。此方法返回替換的值,如果新增新的鍵值對則返回 nil。

語法

以下是 updateValue() 函式的語法:

func updateValue(value, forKey: key) 

示例

import Foundation

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

print("Original Dictionary:", someDict)

// Updating the value of key = 2 with new value
// Using updateValue() function
someDict.updateValue("Four", forKey: 2)

// Displaying output
print("Updated Dictionary:", someDict)

輸出

它將產生以下輸出:

Original Dictionary: [1: "One", 2: "Two", 3: "Three"]
Updated Dictionary: [1: "One", 2: "Four", 3: "Three"]

修改字典中的元素

我們可以使用 [] 在給定鍵處賦值新值來修改字典的現有元素。方括號 [] 更改給定字典中指定鍵的值。

語法

以下是更新值的語法:

Dictionary[key] = value

示例

import Foundation

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

// Updating the value of key = 1 with new value
someDict[1] = "New value of one"

// Displaying the updated value
print("Updated Dictionary:", someDict)
輸出

它將產生以下輸出:

Updated Dictionary: [1: "New value of one", 3: "Three", 2: "Two"]

從字典中移除鍵值對

為了從字典中移除鍵值對,Swift 提供了一個名為 removeValue(forKey:) 的預定義方法。此方法移除指定的鍵及其關聯的值(如果存在),並返回移除的值,如果不存在值則返回 nil。

語法

以下是 removeValue() 屬性的語法:

Dictionary.removeValue(forKey: Key)

示例

import Foundation

// Declaring dictionary
var dict = [101: "Blue", 102: "Pink", 103: "Black", 104: "Brown"]

print("Original Dictionary:", dict)

// Removing a key-Value pair
// Using removeValue() method
dict.removeValue(forKey: 102)

// Displaying output
print("Updated Dictionary:", dict)

輸出

它將產生以下輸出:

Original Dictionary: [102: "Pink", 103: "Black", 104: "Brown", 101: "Blue"]
Updated Dictionary: [103: "Black", 104: "Brown", 101: "Blue"]

一次移除所有元素

Swift 提供了另一個名為 removeAll() 的預定義方法。此方法從給定的字典中移除所有鍵及其關聯的值。

示例

import Foundation

// Declaring dictionary
var dict = [101: "Blue", 102: "Pink", 103: "Black", 104: "Brown"]

print("Original Dictionary:", dict)

// Removing all the key-Value pairs
// Using removeAll() method
dict.removeAll()

// Displaying output
print("Updated Dictionary:", dict)
輸出

它將產生以下輸出:

Original Dictionary: [101: "Blue", 103: "Black", 104: "Brown", 102: "Pink"]
Updated Dictionary: [:]

在 Swift 中迭代字典

為了迭代字典,Swift 提供了 for-in 迴圈。for-in 迴圈迭代字典中的所有鍵值對。

示例

import Foundation

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

// Iterating over the dictionary
// Using for-in loop
for (key, value) in someDict {
   print("Dictionary key \(key) -  Dictionary value \(value)")
}

輸出

它將產生以下輸出:

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

使用 enumerated() 函式

我們還可以將 enumerated() 函式與 for-in 迴圈一起使用,它將返回專案的索引及其 (鍵,值) 對。

示例

import Foundation

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

// Getting the index of the key-value pairs
// Using enumerated() function
for (key, value) in someDict.enumerated() {
   print("Dictionary key \(key) -  Dictionary value \(value)")
}
輸出

它將產生以下輸出:

Dictionary key 0 -  Dictionary value (key: 1, value: "One")
Dictionary key 1 -  Dictionary value (key: 2, value: "Two")
Dictionary key 2 -  Dictionary value (key: 3, value: "Three")

在 Swift 中將字典轉換為陣列

為了將字典轉換為陣列,請從給定的字典中提取鍵值對列表,為鍵和值分別構建陣列。

示例

import Foundation

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

// Declaring two arrays and storing keys and values separately
let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)

// Displaying the arrays
print("Print Dictionary Keys")
for (key) in dictKeys {
   print("\(key)")
}

print("Print Dictionary Values")
for (value) in dictValues {
   print("\(value)")
}

輸出

它將產生以下輸出:

Print Dictionary Keys
1
3
2
Print Dictionary Values
One
Three
Two

字典的“count”屬性

count 屬性用於計算字典中存在的元素總數。

語法

以下是 count 屬性的語法:

Dictionary.count

示例

import Foundation
// Declaring dictionaries
var someDict1 : [Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2 : [Int:String] = [4:"Four", 5:"Five"]

// Counting the elements of dictionaries
// Using count property
var size1 = someDict1.count
var size2 = someDict2.count

print("Total items in someDict1 = \(size1)")
print("Total items in someDict2 = \(size2)")

輸出

它將產生以下輸出:

Total items in someDict1 = 3
Total items in someDict2 = 2

字典的“empty”屬性

empty 屬性用於檢查給定的字典是否為空。如果給定的字典為空,則此屬性將返回 true。如果給定的字典包含一些元素,則此屬性將返回 false。

語法

以下是 empty 屬性的語法:

Dictionary.isEmpty 

示例

import Foundation

// Declaring dictionaries
var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
var someDict3:[Int:String] = [Int:String]()

// Checking if the dictionary is empty or not
// Using isEmpty property
print("someDict1 = \(someDict1.isEmpty)")
print("someDict2 = \(someDict2.isEmpty)")
print("someDict3 = \(someDict3.isEmpty)")

輸出

它將產生以下輸出:

someDict1 = false
someDict2 = false
someDict3 = true
廣告