Swift 基本語法3closure,forEach,map

Astrid
Aug 1, 2021

Trailing Closure

How closure dealing with collections

.forEach

.map return 成指定型別

.compactMap(_:)

flatMap(_:)

Trailing Closure

當closure是最後一個參數時,可以把closure移到小括號外。

How closure dealing with collections

collection有很多swift已經寫好的method用closure來對collection做各種動作。

.forEach

forEach — Loops over a collection and performs an operation

numbers.forEach{ number inprint(number)}

其實跟for in loop 做一樣的事

for number in numbers {print(number)}

.map

map — Loops over an array, executes closure code, returns a new array

.forEach很像,只是它會return新的Array

let numbersSquared = numbers.map { number innumber * number}

.map return 成指定型別

上圖的T是泛型,你要指定他是什麼型別都可以,以下我們要把Double轉換成String,並且只顯示小數點後兩位。

.compactMap(_:)

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

當要對array做一件事,可能會有nil值產生,直接用這個方法,可以幫你把有值的物件形成新的array。

以下我們要把userInput的內容轉成Int,裡面只有一個物件可以轉成功,其他都會是nil。如果我們用for in loop 寫,會像line7–13那樣。

如果用.compactMap(_:)會像line17-19那樣。

flatMap(_:)

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

可以處理多維Array,把它存為一維。

以下要把arrayOfDwarfArrays跑過一次,然後找出字首在M之後的物件,存成新的array。

--

--