Swift字典
Swift 4中的字典是用於存儲相同類型的無序值列表。 Swift 4進行了嚴格的檢查,不允許在字典中輸入錯誤的類型。
Swift 4字典使用稱爲鍵的唯一標識符來存儲值,通過相同的鍵引用和查找值。與數組中的項目不同,字典中的項目沒有指定的順序。 當需要根據標識符(鍵)查找值時,可以使用字典。
字典鍵可以是整數,也可以是字符串,但它在字典中作爲鍵是唯一的。
如果將創建的字典分配給變量,則它始終是可變的,這意味着可以通過添加,刪除或更改其項來更改字典。 但是如果將字典分配給常量,那麼該字典是不可變的,並且其大小和內容不能更改。
1.創建字典
使用以下初始化語法創建特定類型的空字典 -
var someDict = [KeyType: ValueType]()
使用以下簡單語法創建一個空字典,其鍵將是Int
類型,關聯的值是字符串 -
var someDict = [Int: String]()
下面是一個從一組給定值中來創建字典的示例 -
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
2.基於序列的字典初始化
Swift 4允許從數組來創建字典(鍵值對)。
var cities = ["Haikou","Beijing","Nanjing"]
使用以下簡單語法創建一個空字典,其鍵將是Int
類型,關聯的值是字符串 -
var Distance = [2000,10, 620]
下面是一個從一組給定值中來創建字典的示例 -
let cityDistanceDict = Dictionary(uniqueKeysWithValues: zip(cities, Distance))
上面的代碼行將創建一個字典,其中Cities
爲鍵,Distance
爲值 -
3.過濾
Swift 4允許過濾字典中的值。參考以下示例代碼 -
var closeCities = cityDistanceDict.filter { $0.value < 1000 }
如果運行上面的代碼,closeCities
字典將是 -
["Beijing" : 10 , "Nanjing" : 620]
4.字典分組
Swift 4允許創建字典值的分組。參考以下代碼 -
var cities = ["Delhi","Bangalore","Hyderabad","Dehradun","Bihar"]
使用以下簡單語法根據第一個字母對字典值進行分組。
var GroupedCities = Dictionary(grouping: cities ) { $0.first! }
上面代碼的結果將是 -
["D" :["Delhi","Dehradun"], "B" : ["Bengaluru","Bihar"], "H" : ["Hyderabad"]]
5.訪問詞典
使用下標語法從字典中檢索值,並在字典名稱後面的方括號內傳遞要檢索的值的鍵,如下所示 -
var someVar = someDict[key]
查看以下示例來創建,初始化和訪問字典中的值 -
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someVar = someDict[1]
print( "Value of key = 1 is \(someVar)" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )
編譯並執行上述代碼時,會產生以下結果 -
Value of key = 1 is Optional("One")
Value of key = 2 is Optional("Two")
Value of key = 3 is Optional("Three")
修改詞典
使用updateValue(forKey:)
方法將現有值添加到字典的給定鍵。此方法返回字典值類型的可選值。下面是一個簡單的例子 -
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict.updateValue("New value of one", forKey: 1)
var someVar = someDict[1]
print( "Old value of key = 1 is \(oldVal)" )
print( "Value of key = 1 is \(someVar)" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )
編譯並執行上述代碼時,會產生以下結果 -
Old value of key = 1 is Optional("One")
Value of key = 1 is Optional("New value of one")
Value of key = 2 is Optional("Two")
Value of key = 3 is Optional("Three")
通過在給定鍵上分配新值來修改字典的現有元素,如以下示例所示 -
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict[1]
someDict[1] = "New value of one"
var someVar = someDict[1]
print( "Old value of key = 1 is \(oldVal)" )
print( "Value of key = 1 is \(someVar)" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )
編譯並執行上述代碼時,會產生以下結果 -
Old value of key = 1 is Optional("One")
Value of key = 1 is Optional("New value of one")
Value of key = 2 is Optional("Two")
Value of key = 3 is Optional("Three")
刪除鍵值對
使用removeValueForKey()
方法從字典中刪除鍵值對。 此方法刪除鍵值對(如果存在)並返回已刪除的值,如果不存在值則返回nil
。 下面是一個簡單的例子 -
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var removedValue = someDict.removeValue(forKey: 2)
print( "Value of key = 1 is \(someDict[1])" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )
編譯並執行上述代碼時,會產生以下結果 -
Value of key = 1 is Optional("One")
Value of key = 2 is nil
Value of key = 3 is Optional("Three")
還可以使用下標語法通過爲該鍵指定值nil
來從字典中刪除鍵值對。 下面是一個簡單的例子 -
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
someDict[2] = nil
print( "Value of key = 1 is \(someDict[1])" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )
編譯並執行上述代碼時,會產生以下結果 -
Value of key = 1 is Optional("One")
Value of key = 2 is nil
Value of key = 3 is Optional("Three")
迭代字典
可以使用for-in
循環迭代字典中的整組鍵值對,如以下示例所示 -
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (index, keyValue) in someDict.enumerated() {
print("Dictionary key \(index) - Dictionary value \(keyValue)")
}
編譯並執行上述代碼時,會產生以下結果 -
Dictionary key 2 - Dictionary value Two
Dictionary key 3 - Dictionary value Three
Dictionary key 1 - Dictionary value One
可以使用enumerate()
函數返回項目的索引及其(鍵,值)對,如下例所示 -
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
print("Dictionary key \(key) - Dictionary value \(value)")
}
編譯並執行上述代碼時,會產生以下結果 -
Dictionary key 0 - Dictionary value (key: 2, value: "Two")
Dictionary key 1 - Dictionary value (key: 3, value: "Three")
Dictionary key 2 - Dictionary value (key: 1, value: "One")
轉換爲數組
可以從給定字典中提取鍵值對列表,以便爲鍵和值構建單獨的數組。 下面是一個例子 -
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)
print("Print Dictionary Keys")
for (key) in dictKeys {
print("\(key)")
}
print("Print Dictionary Values")
for (value) in dictValues {
print("\(value)")
}
編譯並執行上述代碼時,會產生以下結果 -
Print Dictionary Keys
2
3
1
Print Dictionary Values
Two
Three
One
count屬性
可以使用字典的只讀count
屬性來計算獲得字典中的項目數,如下所示 -
var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
print("Total items in someDict1 = \(someDict1.count)")
print("Total items in someDict2 = \(someDict2.count)")
編譯並執行上述代碼時,會產生以下結果 -
Total items in someDict1 = 3
Total items in someDict2 = 2
count屬性
可以使用字典的只讀empty
屬性來檢查字典是否爲空,如下所示 -
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)")
編譯並執行上述代碼時,會產生以下結果 -
someDict1 = false
someDict2 = false
someDict3 = true