? Swift 語(yǔ)言提供Arrays、Sets和Dictionaries三種基本的集合類(lèi)型用來(lái)存儲(chǔ)集合數(shù)據(jù)。數(shù)組(Arrays)是有序數(shù)據(jù)的集合。集合(Sets)是無(wú)序無(wú)重復(fù)數(shù)據(jù)的集合。字典(Dictionaries)是無(wú)序的鍵值對(duì)的集合。
寫(xiě) Swift 數(shù)組應(yīng)該遵循像Array<Element>這樣的形式,其中Element是這個(gè)數(shù)組中唯一允許存在的數(shù)據(jù)類(lèi)型。我們也可以使用像[Element]這樣的簡(jiǎn)單語(yǔ)法。盡管兩種形式在功能上是一樣的,但是推薦較短的那種。
//數(shù)組初始化
var listTwo = Array<Int>(); //遵循語(yǔ)法方式:空數(shù)組
var listOne = [Int](); //簡(jiǎn)單語(yǔ)法方式:空數(shù)組
var listThree: [Int] = [1, 2, 3]; //字面量數(shù)組
var listFour = [Double](count: 3, repeatedValue: 0.0); //帶默認(rèn)值數(shù)組
var listFive = [Double](count: 4, repeatedValue: 1.0);
var listSix = listFour + listFive; //數(shù)組相加創(chuàng)建數(shù)組
print("The listFive contains \(listFive.count) items."); //只讀屬性count來(lái)獲取數(shù)組中的數(shù)據(jù)項(xiàng)數(shù)量
listOne.isEmpty; //布爾值屬性isEmpty檢查count屬性的值是否為 0//添加元素
listOne.append(3);
listTwo += [4];
listThree.insert(0, atIndex: 0);//獲取數(shù)據(jù)元素
var firstItem = listFive[0];//刪除元素
listSix.removeAtIndex(0);
//listSix.removeLast();
//listSix.removeAll();//數(shù)組遍歷for item in listSix
{print(item);
}for (index, value) in listSix.enumerate() //使用enumerate()方法獲取每個(gè)數(shù)據(jù)項(xiàng)的值和索引值{print("Item \(String(index + 1)): \(value)");
}
Swift 的字典使用Dictionary<Key, Value>定義,其中Key是字典中鍵的數(shù)據(jù)類(lèi)型,Value是字典中對(duì)應(yīng)于這些鍵所存儲(chǔ)值的數(shù)據(jù)類(lèi)型。也可以用[Key: Value]這樣快捷的形式去創(chuàng)建一個(gè)字典類(lèi)型。雖然這兩種形式功能上相同,但是后者是首選。
//字典初始化
var dicTwo = Dictionary<Int, String>(); //標(biāo)準(zhǔn)語(yǔ)法方式
var dicOne = [Int: String](); //快捷語(yǔ)法方式
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來(lái)獲取字典中的數(shù)據(jù)項(xiàng)數(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)");
}