1、添加
- append(_:)在末尾添加一个元素
- append(contentsOf:)在末尾添加多个元素
var array = [1,2,3]
array.append(4)
tempArr = [5,6,7]
array.append(contentsOf: tempArr)
print(array)
打印结果:[1,2,3,4,5,6,7]
2、插入
- insert(_:at:) 在指定位置插入一个元素
- insert(contentsOF:at)在指定位置插入多个元素
var array = [5,6,7]
array. insert(4)
tempArr = [1,2,3]
array. insert(contentsOf: tempArr, at: tempArr.startIndex)
print(array)
打印结果:[1,2,3,4,5,6,7]
3、移出
- 移除单个元素
- remove(at:)移除并返回指定位置的一个元素
- removeFirst()移除并返回数组的第一个元素
- popFirst() 移除并返回数组的第一个元素(optional),数组为空返回nil.
var chars:[Character] = ["a","b","c","d"]
print(chars)
let removedChar = chars.remove(at: 1)
print(removedChar)
print(chars)
let removedChar2 = chars.removeFirst()
print(removedChar2)
print(chars)
结果:
["a", "b", "c", "d"]
b
["a", "c", "d"]
a
["c", "d"]
- 移除多个参数
- removeFirst(:) 移除前面多个元素
- removeList(:)移除后面多个元素
var chars:[Character] = ["a","b","c","d"]
chars.removeFirst(2)
print(chars)
chars.removeLast(2)
print(chars)
结果:
["c", "d"]
[]
- removeSubrange(_:)移除数组中给定范围的元素
- removeAll() 移除数组所有元素
- removeAll(keepingCapacity:)移除所有元素,保留数组容量
var chars:[Character] = ["a","b","c","d"]
chars.removeSubrange(1...2)
print(chars)
chars.insert(contentsOf: "bc", at: 1)
print(chars)
chars.removeAll()
print(chars)
print(chars.capacity)
chars.insert(contentsOf: "abcd", at: 0)
print(chars)
chars.removeAll(keepingCapacity: true)
print(chars)
print(chars.capacity)
结果:
["a", "d"]
["a", "b", "c", "d"]
[]
0
["a", "b", "c", "d"]
[]
4
网友评论