Swift: Functions

Programming

Swift: Functions

9 เดือนที่ผ่านมา

2 min read

Function without Parameters and Return Value

การสร้าง function จะขึ้นต้นด้วย keyword func แล้วตามด้วยชื่อของ function แล้วด้วย () และปิดด้วย {} โดยข้างใน {} จะเป็นส่วนที่ function นั้นทำงาน

func sayHello() {
    print("Hello, Swift!")
}

Calling the function

การเรียกใช้งาน function

// Calling the function
sayHello() // Hello, Swift!

Function with Parameters and Return Value

function แบบนี้ก็จะเป็นประเภทที่เราสามารถส่งเข้าไปทำงานใน function จากนั้นก็จะได้ค่ากลับมา

func add(a: Int, b: Int) -> Int {
    return a + b
}
 
let sum = add(a: 5, b: 3)
print("Sum is \(sum)")

Function with External and Internal Parameter Names

ในภาษา Swift เราสามารถกำหนดชื่อให้กับ parameter ภายในและภายนอก function ได้ อย่างเช่นตัวอย่าง function greet ที่รับ name, hometown เป็นชื่อ parameter ที่ไว้ใช้งานใน function แต่ภายนอก function เราสามารถกำหนดชื่ออื่นได้ เช่น person, from

func greet(person name: String, from hometown: String) {
    print("Hello, \(name)! Glad you could visit from \(hometown).")
}
 
greet(person: "Alice", from: "New York")

ในบางครั้งเราอาจจะไม่อยากได้ชื่อ parameter ภายนอก ก็สามารถใช้ _ เพื่อละเว้นได้

func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}
 
let sum = add(5, 3)
print("Sum is \(sum)")

Default Parameter Values

Default Parameter ก็คือการกำหนดค่าตั้งต้นให้กับ parameter นั้นๆ บางครั้งเราอาจจะไม่ได้ส่งค่าไปให้ function ก็จะใช้ค่าตั้งต้นแทน

func greet(_ name: String, withMessage message: String = "Hello") {
    print("\(message), \(name)!")
}
 
greet("Bob")
greet("Charlie", withMessage: "Hi")

Variadic Parameters

คือ function ที่ไม่ได้กำหนดจำนวน Parameter ที่แน่นอน

func sum(numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total
}
 
let result = sum(numbers: 1.0, 2.0, 3.0, 4.0)
print("Sum is \(result)")

Function as a Parameter

เราสามารถส่ง function เป็น parameter ได้ เช่น

ตัวอย่าง เราจะส่ง function add และ function multiply ไปทำงานใน function calculate ก็จำเป็นต้องกำหนด type และ parameter ต่างๆ ให้เหมือนกัน

// Define a function that takes two integers and returns their sum
func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}
 
// Define a function that takes two integers and returns their product
func multiply(_ a: Int, _ b: Int) -> Int {
    return a * b
}
 
// The calculate function takes two integers and a function as parameters
func calculate(_ operation: (Int, Int) -> Int, _ a: Int, _ b: Int) -> Int {
    return operation(a, b)
}
 
// Now, you can use the calculate function with different operations
let sum = calculate(add, 5, 3) // Pass the 'add' function as a parameter
let product = calculate(multiply, 4, 2) // Pass the 'multiply' function as a parameter
 
print("Sum: \(sum)")
print("Product: \(product)")

Nested Functions:

เราสามารถมี function ซ้อนอยู่ข้างใน function อีกทีได้เหมือนกัน

func outerFunction() {
    func innerFunction() {
        print("Inside the inner function")
    }
 
    print("Inside the outer function")
    innerFunction()
}
 
outerFunction()

Tags:

Swift