Swift 數(shù)組刪除元素

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)元素。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容