基礎(chǔ)知識六:字典

1、Dictionary<Key, Value> 或者 [Key:Value]
2、特性
    a.字典是一種存儲多個相同類型的值的容器;
 b.每個值(value)都關(guān)聯(lián)唯一的鍵(key);
    c.字典中的數(shù)據(jù)項(xiàng)并沒有具體順序;   

1.創(chuàng)建

var tempDic : Dictionary<Int, String>
var tempDic1 = [Int: String]()

//用字典字面量創(chuàng)建字典
var airports: [String: String] = ["key1": "1", "key2": "2"]
var airports1 = ["key1": "1", "key2": "2"]

2、長度

var tempDic1 :[String: String] = ["key1": "1", "key2": "2", "key3": "3"]
print(tempDic1.count)  //3

3.是否為空

var tempDic1 :[String: String] = ["key1": "1", "key2": "2", "key3": "3"]
if !tempDic1.isEmpty {
    print("數(shù)組不為空")
}

4.增

var tempDic1 :[String: String] = ["key1": "1", "key2": "2", "key3": "3"]
tempDic1["key4"] = "4"
print(tempDic1)
//["key2": "2", "key3": "3", "key4": "4", "key1": "1"]

5.刪

var tempDic1 :[String: String] = ["key1": "1", "key2": "2", "key3": "3"]

tempDic1.removeValue(forKey: "key1")
print(tempDic1) //["key2": "2", "key3": "3"]

6.改

var tempDic1 :[String: String] = ["key1": "1", "key2": "2", "key3": "3"]
tempDic1["key1"] = "a"
print(tempDic1)  //["key2": "2", "key3": "3", "key1": "a"]

//updateValue 返回更新值之前的原值; 可選類型
var element1 :String? = tempDic1.updateValue("1", forKey: "key1")
print(element1)  // Optional("a")

7.字典遍歷

var tempDic1 :[String: String] = ["key2": "2", "key3": "3"]
for(key,value) in tempDic1{
    print("\(key) : \(value)")
}
//key2 : 2
//key3 : 3

//遍歷keys
for key in tempDic1.keys{
    print(key)
}
//key2
//key3

//遍歷values
for value in tempDic1.values{
    print(value)
}
//2
//3

8.某個字典的鍵值合構(gòu)型一個數(shù)組

var tempDic1 :[String: String] = ["key2": "2", "key3": "3"]
let keysArr = [String](tempDic1.keys)
print(keysArr)  //["key2", "key3"]

9.keys 或 values排序

print(tempDic1.keys.sorted())
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 53.計(jì)算字符 在字符串中獲取字符值的數(shù)量, 可以使用字符串字符屬性中的計(jì)數(shù)屬性: let unusualMena...
    無灃閱讀 1,269評論 0 4
  • 數(shù)組的概述 PHP 中的數(shù)組實(shí)際上是一個有序圖。圖是一種把 values 映射到 keys 的類型。此類型在很多方...
    dptms閱讀 1,746評論 0 4
  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young閱讀 4,194評論 1 10
  • 我這里在下雨 你那里怎么樣 是否好些了 找到了對的生活對的人 而且學(xué)著冷酷一點(diǎn)? 我確實(shí)還過的可以 工作充實(shí)伙食合...
    老晁閱讀 195評論 0 2
  • A姑娘很久以前看到匡匡的《時有女子》,最后一段是:“我一生渴望被人收藏好,妥善安放,細(xì)心保存。免我驚,免我苦,免我...
    徽喵閱讀 345評論 0 4

友情鏈接更多精彩內(nèi)容