創(chuàng)建數(shù)組
數(shù)組是用來(lái)有序存儲(chǔ)同樣類型的值。同樣的值可以在數(shù)組中不同的位置出現(xiàn)多次。
Swift中數(shù)組中存儲(chǔ)的值類型必須明確,可以通過(guò)類型注釋,也可以通過(guò)類型推斷,并且不能class類型。
下面的例子用來(lái)創(chuàng)建名為shoppingList的數(shù)組來(lái)存儲(chǔ)String值
var shoppingList : [String] = ["Egg","Milk"] ? ? ? ?
//shoppingList has been initialized with two initial items
創(chuàng)建空數(shù)組
????????var someInts = [Int]()
? ? ? ? //數(shù)組設(shè)為空數(shù)組
? ? ? ? someInts = []
? ? ? ? var threeDoubles = [String](repeatElement("123", count:3))//類型是字符串,默認(rèn)是123 長(zhǎng)度是3
由于Swift的類型推斷特性,shoppingList可以簡(jiǎn)寫
var shoppingList = ["Egg","Milk"]
訪問(wèn)和修改數(shù)組
你可以通過(guò)數(shù)組的方法和屬性,或者下標(biāo)語(yǔ)法來(lái)訪問(wèn)和修改數(shù)組
通過(guò)檢查數(shù)組只讀的count屬性來(lái)查看數(shù)組的元素個(gè)數(shù)
print("The shopping list contains \(shoppingList.count)? items.")
使用布爾類型的isEmpty屬性來(lái)判斷count屬性是否為0
? ? ? ? if shoppingList.isEmpty{
? ? ? ? ? ? print("The shopping list is empty.")
? ? ? ? }
? ? ? ? else{
? ? ? ? ? ? print("The shopping list is not empty.")
? ? ? ? }
? ? ? ? 使用append方法來(lái)向數(shù)組中追加一個(gè)新元素
? ? ? ? shoppingList.append("Flour")
? ? ? ? 使用加法賦值運(yùn)算符(+=) 合并數(shù)組
? ? ? ? shoppingList += ["Baking Powder"]
? ? ? ? shoppingList += ["Chocolate Spread","Cheese","Butter"]
? ? ? ? 通過(guò)下標(biāo)語(yǔ)法來(lái)從數(shù)組中獲得一個(gè)值,通過(guò)在數(shù)組名后方緊追一個(gè)方括號(hào)包裹的索引來(lái)訪問(wèn)對(duì)應(yīng)的值:
? ? ? ? var fistItem = shoppingList[0]
? ? ? ? 注意索引上面的第一個(gè)元素的索引是0而不是1
? ? ? ? 你可以通過(guò)下標(biāo)語(yǔ)法來(lái)改變指定索引對(duì)應(yīng)的已存在的值
? ? ? ? shoppingList[0] ="six eggs"
? ? ? ? 你可以通過(guò)下標(biāo)語(yǔ)法來(lái)一次性改變一定范圍內(nèi)的值,即便你要改變的元素個(gè)數(shù)和你提供的元素個(gè)數(shù)不一致也可以。
? ? ? ? shoppingList[4...6] = ["Bananas","Apples"]
? ? ? ? //注意:不能用下標(biāo)語(yǔ)法追加元素
? ? ? ? 插入元素
? ? ? ? shoppingList.insert("Maple Syrup", at:0)
? ? ? ? 刪除元素
? ? ? ? let mapleSyrup = shoppingList.remove(at:0)
? ? ? ? //這個(gè)方法會(huì)返回刪除指定對(duì)應(yīng)的元素(可忽略返回值)
? ? ? ? 刪除最后一個(gè)元素
? ? ? ? let apples = shoppingList.removeLast()
? ? ? ? //刪除第一個(gè) removeFirst
遍歷數(shù)組
for item in shoppingList {
? ? ? ? ? ? print(item)
? ? ? ? }
//遍歷數(shù)組的下標(biāo)和值 enumerated 枚舉的意思
? ? ? ? for (index, value) in shoppingList.enumerated() {
? ? ? ? ? ? print("下標(biāo)\(index) 值為\(value)")
? ? ? ? }