访问和操作数组-添加和删除

2021-06-29  本文已影响0人  一个栗

在末尾添加

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]

在任意位置插入

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

var chars:[Character] = ["a","b","c"]
chars.insert(contentsOf: "hello", at: 0)
print(chars)

运行结果如下:
["h", "e", "l", "l", "o", "a", "b", "c"]

移除单个元素

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"]

移除多个元素

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"]
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
上一篇 下一篇

猜你喜欢

热点阅读