//: Playground - noun: a place where people can play
import UIKit
//字典也叫map 映射
//聲明個空的字典
var Dict0 = Dictionary<Character, Any>()
Dict0.isEmpty //true
//可以直接給字典添加一個key和一個value
Dict0["笑"] = "smile"
//??運算符(類似三目運算符) 意思是當用這個鍵取到的值是nil的時候 可以付給其一個自己定義的值 即下面的"nothing" 只能用于optional形式的數(shù)據(jù)
print(Dict0["笑"] ?? "nothing")
//其中key是hashable的即哈希函數(shù)保存 所以不可通過value逆推key
let Dict = ["蘋果":"apple","桃子":"peach","菠蘿":"pineapple"]
//以下兩種聲明方法
let emptyDict1: [String : String] = [:]
let emptyDict2: Dictionary< String , String> = [:]
//打印可以看出 取出來的值是optional可選型 因為取出來的value可能是空 而且可能key值也不存在呢
for key in Dict.keys{
//系統(tǒng)不知道這個取出來的optional類型的值是空還是什么 所以會報debug警告防止其值為nil 可見swift是十分anquan
//? ? print("\(key) : \(Dict[key]))")
? ? //可以用下面兩種方法消除警告 都是為了防止其值為nil
? ? print("\(key) : \(String(describing: Dict[key])))")
? ? print("\(key) : \(Dict[key] ?? "nothing"))")
}
//字典的安全取值 同樣適用于其他optional變量 這里如果取出來的值是nil 那就不會執(zhí)行{}代碼塊
if let value = Dict["蘋果"]{
?? print(value)
}
for value in Dict.values{
? ? print(value)
}
let Dict1 = ["蘋果":"apple","桃子":"peach","菠蘿":"pineapple"]
let Dict2 = ["蘋果":"apple","桃子":"peach","菠蘿":"pineapple"]
Dict1==Dict2
//注意dictionary是隨機存儲的 所以打印出來與其開始書寫程序不同
for item in Dict {
? ? print(item)
}
//下面是增刪查改操作
var user : [NSString:NSString] = ["username":"Daniel" , "BirthDay":"2.11" , "habit":"play guitar"]
//增加
user["Sex"]="male"
//調(diào)用update方法如果沒有找到該鍵 會自動增加一個鍵
user.updateValue("leftHand", forKey: "girlfriend")
let oldgirlfriend = user["girlfriend"]
user.updateValue("rightHand", forKey: "girfriend")
//注意swift2.0 中if-let-where 語句簡化成 if-let-, 了
if let newgirlfriend = user["girfriend"], oldgirlfriend != newgirlfriend? {
? ? print("Daniel has change a girlfriend")
}
//改
user["habit"]="code"
user.updateValue("play football", forKey: "habit")
//刪除
user["habit"]=nil
user
user.removeValue(forKey: "girlfriend")
user
user.removeAll()