聽說Swift很NB,那麼來勉強學點(3.1)--集合類型數組

數組,是有序數據的集合,存儲的數據值類型必須要明確。 

創建一個空數組 

var someInts = [Int]()
someInts.append(3)
someInts = []
創建一個帶默認值得數組

var threeDoubles = [Double](count:3, repeatedValue:2.5)
//等價於
var threeDoubles:[Double] = [2.5,2.5,2.5]
可以使用加法操作符 + 來組合兩種已存在的相同類型數組,新數組的數據類型會被從兩個數組的數據類型中推斷出來。

var anotherThreeDoubles = Array(count:3, repeatedValue:2.5)
var sixDoubles = threeDoubles + anotherThreeDoubles
用字面量構造數組 

var shoppingList:[String] = ["Eggs","Milk"]
//根據Swift的類型推斷機制,上邊的初始化可以等價於
var shoppingList = ["Eggs","Milk"]
訪問和修改數組 
使用布爾值屬性isEmpty作爲檢查count屬性的值是否爲0 

if shoppingList.isEmpty {
    print("The shopping list is empty")
}else{
    print("The shopping list is not empty")
}
可以使用append(_:)方法在數組後面添加新的數據項 

shoppingList.append("Flour")
使用加法賦值運算符(+=)也可以直接在數組後面添加一個或多個擁有相同類型的數據項 

shoppingList += ["Baking Powder"]
shoppingList += ["Chocolate Spread","Cheese","Butter"]
可以直接使用下標語法來獲取數組中的數據項 

var firstItem = shoppingList[0]
也可以用下標來改變某個已有索引值對應的數據值 

shoppingList[0] = "Six eggs"
還可以用下標來一次改變一系列數據值 

shoppingList[4...6] = ["Bananas","Apples"]
爲數組插入某個值 

shoppingList.insert("Maple Syrup",atIndex:0)
刪除數組的某個值,返回被移除的值 

var removeValue = shoppingList.removeAtIndex(0)
數組的遍歷 

//對數組中的值進行遍歷
for item in shoppingList{
    print(item)
}
//對數組中的索引與值一同遍歷
for (index,value) in shoppingList.enumerate(){
    print("Item \(String(index + 1)):\(value)")
}















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章