数组是有序的,并且数组中的元素是同一种类型
创建空数组
import UIKit
// 创建空数组
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// 数组尾部添加元素
someInts.append(3)
someInts = []
创建有元素数组
// 创建有数组数组
var threeDoubles = Array(count: 3, repeatedValue: 0.0)
var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
var sixDoubles = threeDoubles + anotherThreeDoubles
var shoppingList = ["Eggs", "Milk"]
print("The shopping list contains \(shoppingList.count) items.")
if shoppingList.isEmpty {
print("The shopping list is empty")
} else {
print("The shopping list is not empty")
}
数组添加元素
// 数组添加元素
shoppingList.append("Flour")
print(shoppingList)
shoppingList += ["Baking Powder"]
print(shoppingList)
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
print(shoppingList)
console log结果如下:
数组的增删改访问操作
// 数组访问元素
var firstItem = shoppingList[0]
print(firstItem)
// 修改元素值
shoppingList[0] = "Six Eggs"
print(shoppingList)
shoppingList[4...6] = ["Bananas", "Apples"]
print(shoppingList)
// 插入元素
shoppingList.insert("Maple Syrup", atIndex: 0)
print(shoppingList)
// 移除元素
let mapleSyrup = shoppingList.removeAtIndex(0)
print(mapleSyrup)
print(shoppingList)
// 移除最后一个元素
let lastItem = shoppingList.removeLast()
print(lastItem)
print(shoppingList)
console log结果如下:
数组的遍历
// 遍历数组
for item in shoppingList{
print(item)
}
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
console log结果如下: