数组,是有序数据的集合,存储的数据值类型必须要明确。
创建一个空数组
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)")
}