- 数组的初始化
var numbers = [1, 4, 5, 6]
var numbers1: Array<Int> = [10, 9, 2, 3, 4, 5]
var vowels: [String] = ["a", "e", "i", "o", "u"]
var vowels1: [Character] = ["A", "E", "I", "O", "U"]
var emptyArray: [Int] = []
var emptyArray1 = [Int]()
var allZeros = [Int](repeatElement(0, count: 6)) // [0, 0, 0, 0, 0, 0]
- 数组的成员变量
let vowels = ["a", "e", "i", "o", "u"]
vowels.count //元素的个数
vowels.isEmpty //判断数组是否为空
vowels[2] // “I”
vowels.first! // “a” 声明为常量,一定有值,可以强制解包
vowels.last // “u”
vowels.contains("a") //true
vowels.index(of: "u") // 4
- 遍历
//遍历数组
for vowel in vowels {
print(vowel)
}
//遍历索引和数组(元组)
for (index, vowel) in vowels.enumerated() {
print(index, vowel)
//print("The index is \(index), The element is \(vowel)")
}
var numbers = [1, 4, 5, 6]
numbers.min() // 最小值:1
numbers.max() // 最大值:6
numbers[1..<3] //[4, 5]
numbers[2..<numbers.count] //[5, 6]
- 数组的增删改查
//增
var courses = ["玩转Swift", "玩转Swift第一季", "玩转Swift第二季"]
courses.append("玩转Swift第三季") //在末尾添加元素
courses += ["玩转Swift第四季"] // 同上
courses.insert("Swift协议编程", at: 3) //在“未来”索引处添加元素
//删
courses.removeLast() //删除最后一个元素
courses.removeFirst() //删除第一个元素
courses.remove(at: 3) //删除索引出元素
courses.removeSubrange(0...1) //删除区间内元素
courses.removeAll() //全部删除
//改
courses[0] = "玩转Swift4.0第一季" //直接赋值
courses[0...2] = ["玩转Swift4"] //修改多个