1、 数组初始化
var numbers = [0,1,2,3,4,5]
var vowels = ["A","B","C","D","E"]
//初始化 数组的类型(以Int为例 ):[Int] 或者 Array<Int>
var numbers: [Int] = [0,1,2,3,4,5]
var numbers: Array<Int> = [0,1,2,3,4,5]
// 空数组
var emptyArray2:Array<Int> = []
var emptyArray3:Array<Int> = Array<Int>()
var emptyArray4 = [Int]()
var emptyArray5 = Array<Int>()
// 创建具有默认值的数组(相同元素的数组)
var allZeros1 = Array<Int>(repeating: 0, count: 5) //[0,0,0,0,0]
var allZeros2 = [Int](repeating: 0, count: 5) //[0,0,0,0,0]
2、数组常用方法
// 数组长度
numbers.count
// 判空
numbers.isEmpty
// 获取元素
numbers[2]
// 获取第一个元素和最后一个元素,返回的是可选型
numbers.first
numbers.last
numbers.first!
numbers[numbers.count-1]
// 使用范围
numbers[2..<4] //[3,4]
numbers[2..<numbers.count] //[3,4,5]
// 包含
numbers.contains("3")
let letter = 1
if numbers.contains( letter ){
print("\(letter) is a value")
}else{
print("\(letter) is not a value")
}
// 遍历
for index in 0..<numbers.count{
numbers[index]
}
for number in numbers{
print(number)
}
for (index, number) in numbers.enumerated(){
//遍历数组索引和元素
print("\(index+1): \(number)")
}
// 比较
var oneToFive = [0,1,2,3,4,5]
numbers == oneToFive //true
var oneToFive2 = [0,1,2,4,3,5]
numbers == oneToFive //true swift 3.0之前数组是有序的数据集合,swift 3.0后为无序
var courses = ["A","B","C"]
// 添加元素
courses.append("D") //["A","B","C","D"]
print(courses)
// 数组常量
//使用let定义的数组不可以更改任何内容
courses += ["E"] //+=后面必须和前面的类型一致
print(courses)//["A","B","C","D","E"]
// 两个数组相加
courses = courses + ["F","G"] //+后面必须是数组
print(courses)//["A","B","C","D","E","F","G"]
courses.insert("Q", at: 5)
print(courses)//["A", "B", "C", "D", "E", "Q", "F", "G"]
// 删除元素
courses.removeLast()
print(courses)//["A", "B", "C", "D", "E", "Q", "F"]
courses.removeFirst()
print(courses)//["B", "C", "D", "E", "Q", "F"]
courses.remove(at: 4)
//courses.removeAtIndex(10)
print(courses)//["B", "C", "D", "E", "F"]
//区间删除操作
//courses.removeRange(0..<4)
//courses.removeRange(0..<10)
//print(courses)
//courses.removeAll()
//print(courses)
// 修改元素
courses[0] = "W"
print(courses)//["W", "C", "D", "E", "F"]
//范围修改
courses[1...3] = ["W","W","W"]
print(courses) //["W", "W", "W", "W", "F"]
courses[0...3] = ["W"]
print(courses)//["W", "F"]