在之前的文章中,我們學會了用變數和集合來儲存資料;昨天,我們則掌握了用迴圈來重複執行任務。
但光有材料和重複動作,還無法完成一件作品。我們需要一個能組織指令、執行特定工作的角色,這就是函式(Function)!
函式就像一個獨立的「程式積木」,它將複雜的邏輯封裝起來,方便我們重複使用與維護。今天,就讓我們一起來學習如何打造這些強大又靈活的程式積木!
inout
func 函式名稱(參數列表) -> 返回值型別 {
// 執行內容
return 返回值
}
func sayHello() {
print("哈囉!歡迎參加鐵人賽。")
}
sayHello() // 印出:哈囉!歡迎參加鐵人賽。
定義有參數的函式,以及使用參數標籤提升呼叫時的可讀性:
func sayGreeting(to person: String, from sender: String) {
print("對 \(person) 說:來自 \(sender) 的問候。")
}
sayGreeting(to: "小明", from: "小華")
有時不想在呼叫時輸入參數標籤,可以用底線 _
省略它:
func add(_ a: Int, to b: Int) -> Int {
return a + b
}
add(5, to: 10) // 15
設定參數預設值,呼叫函式時若沒傳入該參數,會自動使用預設值:
func sendMessage(message: String, to recipient: String = "所有使用者") {
print("寄給 \(recipient) 的訊息:\(message)")
}
sendMessage(message: "午安")
sendMessage(message: "吃飯了嗎?", to: "小明")
函式接受可變數量參數,可以傳入任意個同型別參數:
func sum(of numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
使用 inout
參數,在函式內修改外部變數的值:
func double(number: inout Int) {
number *= 2
}
var myNum = 10
print("修改前 myNum 的值是:\(myNum)") // 印出 10
double(number: &myNum)
print("修改後 myNum 的值是:\(myNum)") // 印出 20
函式不只接受參數,也可以回傳結果。
在函式的參數列表後,使用箭頭 ->
來指定返回值型別,並在函式內部使用 return
語句回傳值。
一旦執行 return
,函式會立即結束。
func multiply(a: Int, b: Int) -> Int {
return a * b
}
函式可以一次回傳多個值,使用元組(Tuple)來包裝:
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)
}
if let bounds = minMax(array: [1, 9, 4]) {
print(bounds.min, bounds.max) // 1 9
}
函式本身也是一種型別,可以像變數一樣傳遞與使用:
func add(a: Int, b: Int) -> Int { a + b }
func operate(_ fn: (Int, Int) -> Int, _ x: Int, _ y: Int) {
print("結果是:\(fn(x, y))")
}
operate(add, 3, 5) // 結果是:8
函式還能回傳另一個函式,根據條件動態選擇要執行的邏輯:
func chooseStep(backwards: Bool) -> (Int) -> Int {
return backwards ? { $0 - 1 } : { $0 + 1 }
}
let move = chooseStep(backwards: true)
print(move(5)) // 4
函式內還可以定義函式,組織複雜邏輯並保持程式碼清晰:
func chooseStep2(backwards: Bool) -> (Int) -> Int {
func stepForward(_ x: Int) -> Int { x + 1 }
func stepBackward(_ x: Int) -> Int { x - 1 }
return backwards ? stepBackward : stepForward
}
let step = chooseStep2(backwards: false)
print(step(2)) // 3
今天我們學會了如何打造可重複使用的「程式積木」:函式(Functions)!我們從函式的定義、呼叫、參數與返回值開始,掌握了 inout
、預設值與可變參數等彈性設計。
更進一步,我們探索了 Swift 中函式的強大特性,理解了函式本身也是一種型別,可以作為參數傳遞、當作返回值,甚至在函式內部再定義巢狀函式。善用函式來組織程式碼,是寫出乾淨、模組化且易於維護程式的關鍵!
到目前為止,我們都在使用 Swift 內建的 String
、Int
等現成的「磚塊」來儲存資料。但如果我們想描述一個更複雜的東西,比如一位「使用者」,包含他的名字、等級和積分,該怎麼辦?
明天,我們就要從「使用磚塊」升級為「繪製藍圖」!我們將學習如何使用 struct
(結構體) 和 class
(類別) 來打造專屬於你的自訂資料型別。學會它們,你就能為任何真實世界的物件建立完美的資料模型。
敬請期待《Day 12|Swift 類別與結構:從零打造完美的資料藍圖》