ในภาษา Swift นอกจาก Function จะประกาศเพื่อเรียกใช้งานแล้ว เรายังสามารถกำหนดฟังก์ชั่นให้ตัวแปรได้อีกด้วย ซึ่งทำให้การเขียนโปรแกรมสะดวกมากกว่าเดิม เป็นที่มาของตัวแปรที่เป็นชนิด Function ขึ้นมา เรียกว่า Function Types
ฟังก์ชั่นบวกเลขสองตัว แล้วส่งค่ากลับ
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
ฟังก์ชั่นคูณเลขสองตัว แล้วส่งค่ากลับ
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
return a * b
}
การใช้ตัวแปรแบบฟังก์ชั่น (USING FUNCTION TYPE)
สามารถประกาศตัวแปรแบบ Function Type ได้ดังนี้ var mathFunction : (Int, Int) -> Int จะเห็นว่าชนิดตัวแปรจากปกติจะเป็น Int, String, Double และอื่นตอนนี้กลายเป็น (Int, Int) -> Int ทำให้เราสามารถกำหนดฟังก์ชั่นให้ตัวแปรนี้ได้ และเรียกใช้ตัวแปรนี้เหมือนเป็นฟังก์ชั่นตัวหนึ่งได้เลย
var mathFunction: (Int, Int) -> Int = addTwoInts
print("Result: \(mathFunction(1, 10))")
// prints "Result: 5"
เมื่อต้องการกำหนดฟังก์ชั่นให้ตัวแปร mathFunction ใหม่ ก็สามารถทำได้
mathFunction = multiplyTwoInts(_:_:)
print("Result: \(mathFunction(1, 10))")
การใช้ Function Types เป็นตัวแปรของ Function (FUNCTION TYPES AS Paramter Types)
Function Types ยังสามารถนำไปประยุกต์เป็นตัวแปรของฟังก์ชั่นได้เช่นกัน จากตัวอย่างด้านล่าง
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b:Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts(_:_:), 3, 5)
สังเกตุว่า พารามิเตอร์ตัวแรก เราส่งฟังก์ชั่น addTwoInts( _: _: ) ส่วนตัวที่สองและสามส่งเข้าไปเป็นค่า Int
การใช้ Function Types เป็นตัวคืนค่ากลับ (FUNCTION TYPES AS Return Types)
นอกจากเป็นพารามิเตอร์ของฟังก์ชั่นแล้ว Function Type ก็สามารถนำมาใช้ตอน return หรือคืนค่ากลับได้เหมือนกัน
func stepForward(_ input: Int) -> Int {
return input + 1
}
func stepBackward(_ input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? stepBackward(_:) : stepForward(_:)
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
print("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
print("\(currentValue)...")
currentValue = moveNearerToZero(currentValue)
}
print("zero!")
ฟังก์ชั่น chooseStepFunction จะทำการเลือกว่าจะส่งฟังก์ชั่นไหนกลับไประหว่าง stepBackward หรือ stepForward เพื่อไปให้ moveNearerToZero เรียกใช้งานต่อไป ซึ่งจากตัวอย่างค่า currentValue เป็น 3 จะส่ง stepBackward กลับไปครับ