1.创建空数组
var someInts = [Int]()//空数组 值类型推断为[Int]
someInts.append(3)//包含一个Int值
someInts = []//空数组
2.创建带有默认值的数组
var threeDouble = Array(repeating: 0.0, count: 3)
var threeArray = [Double](repeating: 3.0, count: 3)
// [3.0, 3.0, 3.0] [0.0, 0.0, 0.0]
3. 通过两个数组相加创建一个数组
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
var sixDoubles = threeDouble + anotherThreeDoubles
// [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
4.用数组字面量构造数组
var arr1 = ["zhangsan","lisi"]
var arr2 = [1,2,3,4,5]
// ["zhangsan", "lisi"] [1, 2, 3, 4, 5]
var shoppingList: [String] = ["Eggs","Milk"]
//var shoppingList = ["Eggs","Milk"]
5.数组遍历
1> 普通遍历
for item in shoppingList {
print("普通遍历",item)
}// Eggs Milk
for i in 0..<shoppingList.count {
print("通过count遍历",shoppingList[i])
}// Eggs Milk
2> 同时遍历下标和内容
for e in shoppingList.enumerated() {
print(e)
// print("元组 \(e.offset) \(e.element)")
}// (0, "Eggs") (1, "Milk")
for (index, value) in shoppingList.enumerated() {
print("Item \(index + 1) : \(value)")
}// Item 1 : Eggs Item 2 : Milk
3> 反序遍历
for a in shoppingList.reversed() {
print("反序遍历",a)
}// Milk Eggs
6.访问和修改数组
1> 只读属性count获取数组 数据项数量
shoppingList.count
2> 使用布尔属性isEmpty检查count是否为0
shoppingList.isEmpty
3> append(_:)在数组后面添加新数据
shoppingList.append("Flour")
//["Eggs", "Milk", "Flour"]
4> += 合并(类型必须一致)
shoppingList += ["Baking Powder"]
// ["Eggs", "Milk", "Flour", "Baking Powder"]
shoppingList += ["Chocolatr Spread", "Cheese", "Butter"]
// ["Eggs", "Milk", "Flour", "Baking Powder", "Chocolatr Spread", "Cheese", "Butter"]
5> 通过下标改值
// 下标取值
var firstItem = shoppingList[0]
// 下标改值
shoppingList[0] = "Six eggs"
// ["Six eggs", "Milk", "Flour", "Baking Powder", "Chocolatr Spread", "Cheese", "Butter"]
shoppingList[4...6] = ["Bananas","Apples"]
// ["Six eggs", "Milk", "Flour", "Baking Powder", "Bananas", "Apples"]
6> insert(_:at:) 在索引值之前添加数据
shoppingList.insert("Maple Syrup", at: 0)
// ["Maple Syrup", "Six eggs", "Milk", "Flour", "Baking Powder", "Bananas", "Apples"]
7> remove(at:) 在索引值处移除数据
let milk = shoppingList.remove(at: 2)
// ["Maple Syrup", "Six eggs", "Flour", "Baking Powder", "Bananas", "Apples"]
8> removeLast()移除最后一个
// ["Maple Syrup", "Six eggs", "Flour", "Baking Powder", "Bananas"]
9> removeFirst()移除第一个
// ["Six eggs", "Flour", "Baking Powder", "Bananas"]
10> removeAll(keepingCapacity: true)移除全部并保留空间
// []
11> capacity数组容量
shopping.capacity
// 8