1匙瘪、 數(shù)組初始化
var numbers = [0,1,2,3,4,5]
var vowels = ["A","B","C","D","E"]
//初始化 數(shù)組的類型(以Int為例 ):[Int] 或者 Array<Int>
var numbers: [Int] = [0,1,2,3,4,5]
var numbers: Array<Int> = [0,1,2,3,4,5]
// 空數(shù)組
var emptyArray2:Array<Int> = []
var emptyArray3:Array<Int> = Array<Int>()
var emptyArray4 = [Int]()
var emptyArray5 = Array<Int>()
// 創(chuàng)建具有默認(rèn)值的數(shù)組(相同元素的數(shù)組)
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、數(shù)組常用方法
// 數(shù)組長(zhǎng)度
numbers.count
// 判空
numbers.isEmpty
// 獲取元素
numbers[2]
// 獲取第一個(gè)元素和最后一個(gè)元素窍侧,返回的是可選型
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(){
//遍歷數(shù)組索引和元素
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之前數(shù)組是有序的數(shù)據(jù)集合冻璃,swift 3.0后為無序
var courses = ["A","B","C"]
// 添加元素
courses.append("D") //["A","B","C","D"]
print(courses)
// 數(shù)組常量
//使用let定義的數(shù)組不可以更改任何內(nèi)容
courses += ["E"] //+=后面必須和前面的類型一致
print(courses)//["A","B","C","D","E"]
// 兩個(gè)數(shù)組相加
courses = courses + ["F","G"] //+后面必須是數(shù)組
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"]
//區(qū)間刪除操作
//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"]