關於Swift Dictionary三兩事

對比Array,Dictionary是另一個很常見的資料結構之一,有的程式稱它Object或Map,透過key去存取資料。在搜尋的時間複雜度,Array是Big O(n),因為需要逐一去找,Ditionary是BigO(1),因為透過key就能直接取出。將Dictionary常見操作,整理成筆記,讓swift初學者能快速掌握字典的使用和方便日後查找。

陳仕偉
5 min readAug 2, 2021

如何宣告

宣告一個空的Dictionary

指定變數的資料型態,在用literal語法([:])賦值給變數

var httpStatusDescription: [Int: String] = [:]

用literal語法初始化,指定key和value的資料型態並建立一個空的dictionary

var httpStatusDescription = [Int: String]()

用Dictionary的init方法,指定key和value的資料型態並建立一個空的dictionary

var httpStatusDescription = Dictionary<Int, String>()

宣告有資料的Dictionary

用literal語法,key-value用冒號隔開,不同的key-value用逗號隔開,最後用中括號包起來。另外,swift可以從key和value的值去推斷(infer)資料型態,所以宣告時可以省略資料型態

var httpStatusDescription = [200: "OK", 404: "Page not found"]

先宣告一個空的dictionary,再賦值給變數

var httpStatusDescription = [Int: String]()
httpStatusDescription = [200: "OK", 404: "Page not found"]

key的資料類型

key必須遵照(conform)Hashable協定,有String、integers、floating-point、Boolean、sets、array…等等的,自己定的object,可以conform Hashable協定並實作hash(into:),即可作為key。

var VS let宣告的差別

用var宣告的dictionary是mutable,初始化後仍可以增刪改;用let宣告的dictionary是immutable,初始化後不可以增刪改。

存取資料

新增資料

用subscript語法,當key不存在時,就會將key-value新增至dictioanry

httpStatusDescription[500] = "Internal server error"

透過updateValue(_:forKey:)去更新,當key-value不存在時,會新增一筆新的key-value資料

httpStatusDescription.updateValues("Internal server error", forKey:500)

取出資料

用subscript語法,透過key取出value

var value = httpStatusDescription[200]

更新資料

用subscript語法,將value賦於指定key

httpStatusDescription[200] = "Success"

透過updateValue(_:forKey:)去更新,當key-value不存在時,則會新增一筆新的key-value資料

httpStatusDescription.updateValues("Success", forKey:200)

刪除資料

用subscript語法,將nil賦於指定key

httpStatusDescription[200] = nil

遍歷(iterate)Dictionary

for (code, message) in httpStatusDescription {
print("\\(code): \\(message)")
}

取得所有的keys和values

let keys = httpStatusDescription.keys
let values = httpStatusDescription.values
//將keys轉成array
[Int](keys)
//將values轉成value
[String][values]

透過for-loop遍歷所有的keys和values

for code in keys{
print("code: \\(code)"
}
for message in values{
print("message: \\(message)")
}

檢查Dictionary

檢查dictionary是否為空

guard !httpStatusDescription.isEmpty else{
return
}
//do other something...

檢查dictionary的key-value的總數

guard httpStatusDescription.count > 0 else{
return
}
//do other something...

--

--