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