访问和操作数组-添加和删除
2021-06-29 本文已影响0人
一个栗
在末尾添加
- append(_:) 在末尾添加一个元素
- append(contentsOf:) 在末尾添加多个元素
var numbers = [Int](2...7)
numbers.append(100)
print(numbers)
numbers.append(contentsOf: 100...105)
print(numbers)
运行结果如下:
[2, 3, 4, 5, 6, 7, 100]
[2, 3, 4, 5, 6, 7, 100, 100, 101, 102, 103, 104, 105]
在任意位置插入
- insert(_:at:) 在指定的位置插入一个元素
- insert(contentsOf:at:) 在指定位置插入多个元素
var numbers = [Int](2...7)
numbers.insert(-1, at: 0)
print(numbers)
numbers.insert(contentsOf: -2...0, at: 0)
print(numbers)
运行结果如下:
[-1, 2, 3, 4, 5, 6, 7]
[-2, -1, 0, -1, 2, 3, 4, 5, 6, 7]
字符串也是 Collection
- 字符串也是 Collection, Element 是 Character 类型
var chars:[Character] = ["a","b","c"]
chars.insert(contentsOf: "hello", at: 0)
print(chars)
运行结果如下:
["h", "e", "l", "l", "o", "a", "b", "c"]
移除单个元素
- remove(at:) 移除并返回指定位置的第一个元素
- removeFirst() 移除并返回数组的第一个元素【数组为空时会报错】
- popFirst() 移除并返回数组的第一个元素(optional)【数组为空返回nil】
var chars:[Character] = ["a","b","c","d"]
let removedChar = chars.remove(at: 1)
print(removedChar)
print(chars)
运行结果如下:
b
["a", "c", "d"]
var chars:[Character] = ["a","b","c","d"]
let removedChar = chars.removeFirst()
print(removedChar)
print(chars)
运行结果如下:
a
["b", "c", "d"]
var chars:[Character] = ["a","b","c","d"]
chars.popLast()
print(chars)
运行结果如下:
["a", "b", "c"]
移除多个元素
- removeFirst(:) 移除数组前面多个元素
- removeLast(:) 移除数组后面多个元素
var chars:[Character] = ["a","b","c","d"]
chars.removeFirst(2)
print(chars)
运行结果如下:
["c", "d"]
var chars:[Character] = ["a","b","c","d"]
chars.removeLast(2)
print(chars)
运行结果如下:
["a", "b"]
- removeSubrange(_:) 移除数组中给定范围的元素
- removeAll() 移除数组所有元素
- removeAll(keepingCapacity:) 移除数组所有元素,保留数组容量【建议使用】
var chars:[Character] = ["a","b","c","d"]
chars.removeSubrange(1...2)
print(chars)
运行结果如下:
["a", "d"]
var chars:[Character] = ["a","b","c","d"]
chars.removeAll()
print(chars)
print(chars.capacity)
运行结果如下:
[]
0
var chars:[Character] = ["a","b","c","d"]
chars.removeAll(keepingCapacity: true)
print(chars)
print(chars.capacity)
运行结果如下:
[]
4