0

## IOS Swift 還能更精簡? Closure的其它用法你一定要知道！！

### 開始囉

``````let numArray = [1,3,5,7,9]
``````

``````numArray.map({
(num:Int)->Int in
return num+1
})
``````

``````let newArray = numArray.map({
(num:Int)->Int in
return num+1
})

print(newArray)
// [2,4,6,8,10]

``````

### 哪泥～還可以簡寫！！

``````let newArray2 = numArray.map({
(num:Int)->String in
return "new number \(num)"

``````
##### 開始簡寫
1. 若已經知道參數及回傳值的型別的話，則可以刪除closure內參數及回傳值的型別
• 根據上面的資訊我們知道了每次傳入都是整數而會傳的而也是字串。
``````let newArray2 = numArray.map({
(num)in
return "new number \(num)"
``````
2. 若程式碼只有一行的情況下可以省略return，因為此時系統會幫你預設return
• 很明顯的他只有一行
``````let newArray2 = numArray.map({
(num) in "new number \(num)"
``````
3. 可以利用\$0、\$1、\$2..，代替進去的參數名稱
``````let newArray2 = numArray.map({
"new number \(\$0)"
})
print(newArray2)
//["new number 1","new number 3","new number 5","new number 7","new number 9"]
``````

### 還嫌太多～還能在簡寫嗎?

1. 如果Closure是函式最後一個參數時則可以把它放到括號的後面。

• 我們很明顯的可以觀察到在map裡面的函式是以Closure當作最後一個參數，所以我們可以將它放到括號的後面。
``````let newArray2 = numArray.map(){  "new number \(\$0)" }
``````
2. 如果Closure是函式唯一的參數時則可以把小括號拿掉

• 如果Closure是函式唯一的參數除上述做法也把小括號拿掉
``````let newArray2 = numArray.map{  "new number \(\$0)" }

print(newArray2)
// ["new number 1","new number 3","new number 5","new number 7","new number 9"]
``````