Swift 數(shù)組里提供了刪除數(shù)組元素的方法主要包括以下幾種:
1、@inlinable public mutating func remove(at index: Int) -> Element
通過索引刪除元素,且索引必須是數(shù)組有效索引,返回刪除所索引元素。
復(fù)雜度為 O(n)
remove(at index: Int)示例
var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]
let removed = measurements.remove(at: 2)
print(measurements)
// Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]"
@inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false)
刪除數(shù)組所有元素
參數(shù)keepCapacity 為true保持當(dāng)前數(shù)組容量,默認(rèn)值為false。
復(fù)雜度為O(n)
Swift數(shù)組如果要?jiǎng)h除某個(gè)元素,那么我們有哪些方式呢?
一個(gè)簡單的方法是我們通過filter直接過濾掉我們需要生成的元素:
let ar = [2, 3, 5, 34]
// 生成新數(shù)組
let ar2 = ar.filter({$0 != 2})
print(ar2)
// 過濾未包含元素
let ar3 = ar.filter({$0 != 7})
print(ar3)
但是這種方法會(huì)生成一個(gè)新的數(shù)組,如果我們不想生成一個(gè)新的數(shù)組,還在原來的數(shù)組上操作該怎么做呢?
一、使用removeAll(where:)
@inlinable public mutating func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows
使用這個(gè)方法刪除數(shù)組中的每一個(gè)匹配的元素
復(fù)雜度為O(n)
removeAll(where:)示例:
刪除數(shù)組中的奇數(shù)
var numbers = [5, 6, 7, 8, 9, 10, 11]
numbers.removeAll(where: { $0 % 2 != 0 })
// numbers == [6, 8, 10]
刪除數(shù)組中的某個(gè)元素
var ar = [2, 3, 2, 5, 34]
ar.removeAll(where: {$0==2})
// ar = [3, 5, 34]
二、使用remove(at:)
思路大概就是找到需要?jiǎng)h除數(shù)組索引進(jìn)行刪除,在OC里我們可以通過indexOfObject:方法獲取索引,在Swift里我們可以通過以下方法獲取索引:
1、index(of:)獲取數(shù)組里元素出現(xiàn)的第一個(gè)索引,但是從Swift5.0開始,這個(gè)方法被廢棄了。
@inlinable public func index(of element: Element) -> Int?
2、firstIndex(of:)在使用firstIndex(of :)查找特定元素的位置。
@inlinable public func firstIndex(of element: Element) -> Int?
firstIndex(of:)使用示例:
var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
students[i] = "Max"
}
print(students)
// Prints "["Ben", "Ivy", "Jordell", "Max"]"
OK,接下來我們來進(jìn)行對(duì)原數(shù)組操作進(jìn)行元素刪除:
var ar = [2, 3, 5, 34]
// 原數(shù)組操作
// 刪除元素 3
if let index = ar.firstIndex(of: 3) {
ar.remove(at: index)
}
// 測(cè)試刪除未含元素
if let index = ar.firstIndex(of: 6) {
ar.remove(at: index)
}
寫在最后:
使用方法一可以把所有需要?jiǎng)h除的元素刪除,使用方法二可以刪除第一個(gè)目標(biāo)元素。當(dāng)然也可以使用lastIndex(of: )刪除最后一個(gè)目標(biāo)元素。