Swift 數(shù)組處理

使用 filter 方法

filter 方法允許你根據(jù)一個(gè)條件過濾數(shù)組中的元素。它返回一個(gè)包含所有滿足條件的元素的新數(shù)組。

let numbers = [1, 2, 3, 4, 5, 6]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers)  // 輸出: [2, 4, 6]

使用 compactMap 方法

如果你需要過濾并轉(zhuǎn)換數(shù)組中的元素,可以使用 compactMap。它類似于 map 方法,但是它會移除任何 nil 值。

let strings = ["1", "two", "3", "four", "5"]
let numbersFromString = strings.compactMap { Int($0) }
print(numbersFromString)  // 輸出: [1, 3, 5]

map

不改變原數(shù)組

let numbers = [1, 2, 3, 4, 5]
let doubledNumbers = numbers.map { $0 * 2 }
print(doubledNumbers)  // 輸出: [2, 4, 6, 8, 10]

使用 flatMap 方法

flatMap 方法通常用于處理嵌套數(shù)組,但也可以用來過濾數(shù)組。它首先將每個(gè)元素映射到一個(gè)新數(shù)組,然后扁平化這些數(shù)組。

let numbers = [1, 2, 3, 4, 5, 6]
let evenNumbersFlatMap = numbers.flatMap { $0 % 2 == 0 ? [$0] : [] }
print(evenNumbersFlatMap)  // 輸出: [2, 4, 6]

使用 remove(where:) 方法

如果你只是想從數(shù)組中移除滿足條件的元素,而不是創(chuàng)建一個(gè)新的數(shù)組,可以使用 remove(where:) 方法。

var numbers = [1, 2, 3, 4, 5, 6]
numbers.removeAll(where: { $0 % 2 != 0 })
print(numbers)  // 輸出: [2, 4, 6]

使用 removeAll 方法(不帶條件)

如果你想移除數(shù)組中的所有元素,可以使用 removeAll 方法。

var numbers = [1, 2, 3, 4, 5, 6]
numbers.removeAll()
print(numbers)  // 輸出: []
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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