0
点赞
收藏
分享

微信扫一扫

swift 数组的添加和删除

飞进科技 2023-03-10 阅读 62


append(_:)在末尾添加一个元素

append(contentsOf:)在末尾添加多个元素

//: A UIKit based Playground for presenting user interface

import UIKit
var array = [(42,"erro2"),(41,"erro1"),(43,"erro3")]
array.append((40,"error0"))
array.append(contentsOf: [(42,"erro2"),(41,"erro1")])
print(array)

[(42, "erro2"), (41, "erro1"), (43, "erro3"), (40, "error0"), (42, "erro2"), (41, "erro1")]

同理也有

insert(_:at:) 在指定位置插入一个元素

insert(contentsOF:at)在指定位置插入多个元素

//: A UIKit based Playground for presenting user interface

import UIKit
var array = [(42,"erro2"),(41,"erro1"),(43,"erro3")]
array.insert((40,"error0"),at: 0)
array.insert(contentsOf: [(42,"erro2"),(41,"erro1")],at: array.endIndex)
print(array)

[(40, "error0"), (42, "erro2"), (41, "erro1"), (43, "erro3"), (42, "erro2"), (41, "erro1")]

字符串也是Collection

字符串也是Collection Element时Character类型

["d", "e", "f", "g", "h", "a", "b", "c"]

移除单个元素

remove(at:)移除并返回指定位置的一个元素

removeFirst()移除并返回数组的第一个元素

popFirst() 移除并返回数组的第一个元素(optional),数组为空返回nil.

//: A UIKit based Playground for presenting user interface

import UIKit

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(:)移除后面多个元素

//: A UIKit based Playground for presenting user interface

import UIKit

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

["c", "d"]

[]

removeSubrange(_:)移除数组中给定范围的元素

removeAll() 移除数组所有元素

removeAll(keepingCapacity:)移除所有元素,保留数组容量

//: A UIKit based Playground for presenting user interface

import UIKit

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

 

举报

相关推荐

0 条评论