程序员

swift 数组添加与删除

2022-11-10  本文已影响0人  心猿意码_
1、添加
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、插入
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、移出
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"]

var chars:[Character] = ["a","b","c","d"]
chars.removeFirst(2)
print(chars)
chars.removeLast(2)
print(chars)

结果:

["c", "d"]

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

猜你喜欢

热点阅读