Closure
Closure คือ กลุ่มของคำสั่ง ซึ่งสามารถถูกประกาศและถูกใช้ในส่วนต่างๆ ของโค้ด
การใช้ Closure ในภาษา Swift นั้น มีความคล้ายกับการใช้งาน Lambda expression ในการเขียนโปรแกรมด้วยภาษา java หรือ C# ซึ่งจะช่วยให้เราสามารถเขียนคำสั่งได้สั้นและง่ายขึ้น รูปแบบทั่วไปของ Closure มีลักษณะดังนี้
{
(parameter type, parameter type) -> return ReturnType in
// คำสั่งเพื่อระบุการทำงานของ closure
}ตัวอย่างการลดรูปการเขียนคำสั่งโดยใช้ Closure
//ตัวอย่างในการใช้งาน Function Type
func addTwoInt(_ firstInt: Int, _ secondInt: Int) -> Int {
return firstInt + secondInt
}
var myFunc: (Int, Int) -> Int
myFunc = addTwoInt
print(myFunc(7, 5)) // 12เราอาจสามารถลดรูปได้ดังนี้
var myFunc = {
(firstInt: Int, secondInt: Int) -> Int in
return firstInt + secondInt
}
print(myFunc(7, 5)) // 12(1) การใช้ Closure ในรูปแบบที่ไม่มีการส่งค่ากลับ
(2) การใช้ Closure ในแบบพารามิเตอร์
แหล่งข้อมูลอ้างอิง
The Swift Programming Language (Swift 5.5), Apple Inc., 2019. Available on: Apple Book Store.
App Development with Swift, Apple Inc., 2017. Available on: Apple Book Store.
Last updated