数组用来按照顺序存储相同类型的数据,相同的值可以多次出现在同一数组的不同位置.
Swift数组对存储数据的具体要求:数据值在被存储进入某个数组之前类型必须明确,方法是通过显示的类型标注或者类型推断,而且不是必须是class类型.Swift中的数组是类型安全的,并且他们中包含的类型必须明确.
一.数组的构造语句
1.var shopList: [String] = ["milk", "eggs"]
2.var shopList = ["milk", "eggs"] //因为值都是相同类型的,所以Swift会进行类型推断
3.var shopList = Array<String>()
4.var shopList = Array<String>.init()
二.访问和修改数组
//获取数组数据项数量
print("\(shoppingList.count)")
//使用isEmpty检查数组中数据项数量是否为0
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
//使用append方法在数组后面添加新的数据项
shoppingList.append("apple")
//使用加法赋值运算符(+=)直接添加拥有相同类型数据的数组
shoppingList += ["Chocolate Spread", "Cheese", "Butter", "orange"]
//获取数组中的数据项
var firstItem = shoppingList[0]
var subList = shoppingList[4...6]
//更改数组中的数据项
firstItem = "Six eggs"
shoppingList[4...6] = ["Bananas", "Apples"]
//调用数组的insert(atIndex:)方法来在某个具体索引值之前添加数据项:
shoppingList.insert("Maple Syrup", at: 0)
//移除指定索引数据
let mapleSyrup = shoppingList.remove(at: 0)
//删除最后一项
let apples = shoppingList.removeLast()
//删除第一项
let orange = shoppingList.removeFirst()
//遍历数组
for item in shoppingList {
print(item)
}
for (index, value) in shoppingList.enumerated() {
print("Item \(index + 1): \(value)")
}
二.数组数据排序
整数数组排序
var intArray = [6, 1, 11, 3, 8, 10, 22]
let sortA = intArray.sorted() //默认排序为升序
print(sortA)
打印结果:[1, 3, 6, 8, 10, 11, 22]
let sortB = intArray.sorted { (a, b) -> Bool in
a > b //降序
}
print(sortB)
打印结果:[22, 11, 10, 8, 6, 3, 1]
//字符串数组排序
var stringArray = ["bnanana", "orange", "apple"]
let sortC = stringArray.sorted()
print(sortC)
打印结果:["apple", "bnanana", "orange"]
let sortD = stringArray.sorted { (a, b) -> Bool in
a > b 降序
}
print(sortD)
打印结果:["orange", "bnanana", "apple"]