? Swift 語言提供Arrays、Sets和Dictionaries三種基本的集合類型用來存儲集合數(shù)據(jù)。數(shù)組(Arrays)是有序數(shù)據(jù)的集合。集合(Sets)是無序無重復(fù)數(shù)據(jù)的集合。字典(Dictionaries)是無序的鍵值對的集合。
Swift 的字典使用Dictionary<Key, Value>定義,其中Key是字典中鍵的數(shù)據(jù)類型,Value是字典中對應(yīng)于這些鍵所存儲值的數(shù)據(jù)類型。也可以用[Key: Value]這樣快捷的形式去創(chuàng)建一個字典類型。雖然這兩種形式功能上相同,但是后者是首選。
//字典初始化
var dicTwo = Dictionary<Int, String>(); //標準語法方式
var dicOne = [Int: String](); //快捷語法方式
var dicThree : [String: String] = ["Gof": "Ligaofeng", "Dub": "Dublin"]; //字面量創(chuàng)建字典
var dicFour = ["Gof": "Ligaofeng", "Dub": "Dublin", "YYZ": "Toronto Pearson"];print("The dicThree contains \(dicThree.count) items."); //只讀屬性count來獲取字典中的數(shù)據(jù)項數(shù)量
dicThree.isEmpty; //布爾值屬性isEmpty檢查count屬性的值是否為 0//獲取/修改數(shù)據(jù)元素
var item = dicFour["Gof"];
dicFour["Chief"] = "Chief GO";
let oldValue = dicFour.updateValue("LiGaoFeng", forKey: "Gof");
let delValue = dicFour.removeValueForKey("Gof");//遍歷for (key, value) in dicFour
{print("\(key): \(value)");
}for key in dicThree.keys
{print("Key: \(dicThree)");
}for value in dicThree.values
{print("Value: \(value)");
}