Swift 函数基础语法Swift 函数通过func关键字定义基本语法如下func functionName(parameters) - ReturnType { // 函数体 return value }示例无参数函数func greet() - String { return Hello, Swift! } print(greet()) // 输出 Hello, Swift!示例带参数的函数func add(a: Int, b: Int) - Int { return a b } print(add(a: 2, b: 3)) // 输出 5参数标签与外部参数名Swift 支持为参数添加外部标签增强可读性func greet(person name: String) - String { return Hello, \(name)! } print(greet(person: Alice)) // 输出 Hello, Alice!忽略外部参数名使用_省略外部标签func multiply(_ a: Int, _ b: Int) - Int { return a * b } print(multiply(4, 5)) // 输出 20默认参数值函数参数可以设置默认值func power(_ base: Int, exponent: Int 2) - Int { return Int(pow(Double(base), Double(exponent))) } print(power(3)) // 输出 9 (默认 exponent2) print(power(3, exponent: 3)) // 输出 27可变参数使用...表示可变参数func sum(_ numbers: Int...) - Int { var total 0 for num in numbers { total num } return total } print(sum(1, 2, 3, 4)) // 输出 10函数作为参数与返回值Swift 函数是一等公民可作为参数或返回值传递func applyOperation(_ a: Int, _ b: Int, operation: (Int, Int) - Int) - Int { return operation(a, b) } let result applyOperation(10, 5, operation: { $0 - $1 }) print(result) // 输出 5返回函数的函数func chooseOperation(_ isAdd: Bool) - (Int, Int) - Int { return isAdd ? () : (-) } let operation chooseOperation(false) print(operation(8, 3)) // 输出 5嵌套函数函数可以嵌套定义func outerFunction() - () - Void { var counter 0 func innerFunction() { counter 1 print(Counter: \(counter)) } return innerFunction } let counterFunc outerFunction() counterFunc() // 输出 Counter: 1 counterFunc() // 输出 Counter: 2函数重载Swift 支持函数重载相同函数名不同参数类型或数量func process(_ value: Int) { print(Processing Int: \(value)) } func process(_ value: String) { print(Processing String: \(value)) } process(42) // 输出 Processing Int: 42 process(Swift) // 输出 Processing String: Swift泛型函数使用泛型增强函数灵活性func swapValuesT(_ a: inout T, _ b: inout T) { let temp a a b b temp } var x 10, y 20 swapValues(x, y) print(x\(x), y\(y)) // 输出 x20, y10逃逸闭包与非逃逸闭包默认闭包为非逃逸noescape需显式标记逃逸闭包var completionHandlers: [() - Void] [] func withEscapingClosure(completion: escaping () - Void) { completionHandlers.append(completion) } withEscapingClosure { print(Escaping closure executed) } completionHandlers.first?() // 输出 Escaping closure executed自动闭包延迟求值的闭包func debugLog(_ condition: autoclosure () - Bool) { if condition() { print(Debug: Condition is true) } } debugLog(1 2) // 输出 Debug: Condition is true通过以上示例可以全面掌握 Swift 函数的核心特性与实际应用场景。