swift 数组的添加和删除

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值