[Swift] Array 陣列快速過濾函式 filter 的使用教學

在 Swift 中,如果我們要過濾出陣列中的某些元素,最常用的就是 for-in loop 了,使用迴圈來過濾固然是一個不錯的方式,但在追求精簡的 Swift 就顯得笨重許多了。Swift 提供了另一個過濾的方式,叫做 filter,只要能善用 filter,就能讓你的程式碼精簡許多,接下來我們來看一下 swift 的 filter 怎麼使用吧!

swift

首先,先看一下 filter 的函式原型。

func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]

那我們該怎麼用呢?很簡單,只要「陣列名稱.filter {條件}」或者 「陣列名稱.filter( {條件} )」就好了。舉例如下:

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"

困擾的來了,$0 這代表什麼意思呢?其實你可以把 $0 看做陣列的元素, 以上例來說,就是 cast[0]、cast[1]、cast[2]…,所以 $0 物件的型態是  String,所以以上例來說,就會把長度是 5 以下的字串,再組合成一個新的陣列。

而以下為傳統的寫法,使用 for-in loop (Swift 控制流程 for-in Loop 教學)來寫。

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
var shortNames: [String] = []

for str in cast {
    if str.count < 5 {
        shortNames.append(str)
    }
}

print(shortNames)
// Prints "["Kim", "Karl"]"

相較於舊的寫法, filter 顯得更精簡,但時間複雜度都是 O(n) 喔!

Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] [Swift] Array 陣列的快速過濾 filter 的使用教學 […]