数组基本操作

Array

定义空Array

var array1: Array = Array()
var array2: [Int] = []
var array3 = array2

Array赋值

var threeInts = [Int](repeating: 3, count: 3)
var sixInts = threeInts + threeInts
var fiveInts = [1,2,3,4,5]

元素判断与获取

//判断元素个数
fiveInts.count
//判断是否为空
array1.isEmpty
//获取元素
fiveInts[2]
//通过下标集合获取的元素集合为ArraySlice而非Array
type(of: fiveInts[0..<2])
fiveInts[0...2]

遍历Array

for value in fiveInts {
    print(value)
}

for (index, value) in fiveInts.enumerated() {
    print("\(index):\(value)")
}

fiveInts.forEach { print($0) }

for in 与 forEach的区别

Array元素修改

//添加元素
array1.append(1)
array1 += [2,3,4]

//插入元素
array1.insert(0, at: array1.startIndex)

//删除元素
array1.remove(at: 4)
array1.removeLast()
array1.popLast())

你可能感兴趣的:(数组基本操作)