今天要來介紹一個 Swift 中非常特別又強大的語法 —— 閉包(Closure)!
閉包可以想成是「可以被儲存、傳遞的 function」,功能上跟 function 非常像,但更靈活、更自由!
在加上必包有著可以捕捉並保存它周圍上下文的變數值
你也可以把它想像成是「沒有名字的 function」,超好用又常見喔!
我們同樣先來介紹閉包的格式
{ (參數) -> 回傳型別 in
//程式區塊
}
相信大家注意到了是不是長得跟 function 很像!
差別就是它沒有 func 和名字,還多了一個 in
關鍵字來分隔參數與執行內容。
今天我們一樣先來看例子再介紹
//function 寫法
func fruitPrice() -> String {
let apple = 15
let grape = 10
if apple > grape {
return "蘋果比較貴"
} else {
return "葡萄比較貴"
}
}
let result = fruitPrice()
print(result) // ➜ 輸出:蘋果比較貴
//closure 寫法
let fruitPrice = { (apple: Int, grape: Int) -> String in
if apple > grape {
return "蘋果比較貴"
} else {
return "葡萄比較貴"
}
}
let result = fruitPrice(15, 10)
print(result) // ➜ 輸出:蘋果比較貴
相信大家已經看出來差別了,閉包不但可以被存在變數裡
而且我們直接用變數名
就能呼叫它!
let fruitPrice = { (fruit: String, price: Int) in
print("\(fruit)要\(price)元喔!")
}
fruitPrice("木瓜", 20) //輸出 "木瓜要20元喔!"
let priceSum: (Int, Int) -> Int = { $0 * $1 }
let result = priceSum(20, 15) // result 為 300
@escaping
關鍵字。@escaping
。func fetchFruitName(completion: @escaping (String) -> Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
completion("香蕉")
}
}
fetchFruitName { fruit in
print("今天吃的是:\(fruit)") // 兩秒後輸出:今天吃的是:香蕉
}