func add(a: Int, b: Int) -> Int {
return a + b
}
let result = add(a: 5, b: 3) // 返回 8
print(result) // 输出:8
2. 参数标签与参数名称 —— 具名参数
Swift 的函数允许为参数定义外部参数标签和内部参数名称,提高可读性。
外部和内部参数名称
func greet(person name: String, from city: String) {
print("Hello \(name)! How's the weather in \(city)?")
}
greet(person: "Bob", from: "San Francisco") // 输出:Hello Bob! How's the weather in San Francisco?
省略参数标签
如果不需要外部参数标签,可以使用 _ 来省略:
func multiply(_ a: Int, _ b: Int) -> Int {
return a * b
}
let product = multiply(3, 4) // 输出:12
func sum(of numbers: Int...) -> Int {
return numbers.reduce(0, +)
}
let total = sum(of: 1, 2, 3, 4) // 输出:10
5. 返回多个值(元组)
函数可以通过返回一个元组来返回多个值。
func minMax(numbers: [Int]) -> (min: Int, max: Int)? {
if numbers.isEmpty { return nil }
var currentMin = numbers[0]
var currentMax = numbers[0]
for number in numbers {
if number < currentMin {
currentMin = number
} else if number > currentMax {
currentMax = number
}
}
return (currentMin, currentMax)
}
if let bounds = minMax(numbers: [8, -6, 2, 109, 3, 71]) {
print("Min: \(bounds.min), Max: \(bounds.max)")
}
6. 函数类型
函数本身是一种类型,因此可以将函数作为参数传递给其他函数,或作为函数的返回值。
将函数作为参数传递
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
func multiply(_ a: Int, _ b: Int) -> Int {
return a * b
}
func operate(_ a: Int, _ b: Int, using operation: (Int, Int) -> Int) -> Int {
return operation(a, b)
}
let sum = operate(4, 2, using: add) // 输出:6
let product = operate(4, 2, using: multiply) // 输出:8