Swift 函式(Functions)

函式是執行特定任務的獨立程式碼塊。Swift 的函式語法非常靈活,從最簡單的不帶參數函式,到帶有參數標籤和預設值的複雜函式都能支援。

定義與呼叫函式

使用 func 關鍵字來定義函式:

func greet(person: String) -> String {
    let greeting = "Hello, " + person + "!"
    return greeting
}
  • person: String:定義參數名稱和型別。
  • -> String:定義回傳值的型別。

呼叫函式時,必須寫出參數標籤 (Argument Label):

print(greet(person: "Anna"))
// 輸出 "Hello, Anna!"

參數與回傳值

多重回傳值 (使用元組)

func minMax(array: [Int]) -> (min: Int, max: Int)? {
    if array.isEmpty { return nil }
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1..<array.count] {
        if value < currentMin { currentMin = value }
        else if value > currentMax { currentMax = value }
    }
    return (currentMin, currentMax)
}

函式參數標籤 (Argument Labels)

每個參數都有由一個引數標籤 (Argument Label) 和一個參數名稱 (Parameter Name) 組成。

  • 引數標籤:在呼叫函式時使用。
  • 參數名稱:在函式內部實作時使用。

預設情況下,引數標籤等於參數名稱。

// 指定標籤: "from" 是引數標籤,"hometown" 是參數名稱
func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)! Glad you could visit from \(hometown)."
}

print(greet(person: "Bill", from: "Cupertino"))

省略引數標籤

如果你不希望在呼叫時寫標籤,可以使用底線 _

func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
    // ...
}

someFunction(1, secondParameterName: 2)

預設參數值

你可以給參數一個預設值,這樣呼叫時就可以省略該參數:

func someFunction(parameterWithDefault: Int = 12) {
    // ...
}
someFunction(parameterWithDefault: 6) // 使用 6
someFunction() // 使用預設值 12

可變參數 (Variadic Parameters)

使用 ... 來接受不確定數量的參數 (會被視為陣列):

func arithmeticMean(_ numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}

arithmeticMean(1, 2, 3, 4, 5)

函式型別 (Function Types)

在 Swift 中,函式本身也是一種型別。你可以將函式賦值給變數,或當作參數傳遞。

func addTwoInts(_ a: Int, _ b: Int) -> Int {
    return a + b
}

var mathFunction: (Int, Int) -> Int = addTwoInts
print("Result: \(mathFunction(2, 3))")