一个简单的函数包含函数名、参数列表(可选)和返回值类型(可选)
在 Swift 中,函数是组织代码的基本单元,用于封装可重用的逻辑。函数通过 func 关键字定义,并可以接受参数、返回值,甚至可以嵌套在其他函数中。以下是创建和使用 Swift 函数的详细说明和示例:
1. 基本函数定义
一个简单的函数包含函数名、参数列表(可选)和返回值类型(可选)。
swift
func sayHello() {
print("Hello, World!")
}
// 调用函数
sayHello() // 输出: Hello, World!
2. 带参数的函数
函数可以接受一个或多个参数,参数需要指定名称和类型。
swift
func greet(name: String) {
print("Hello, \(name)!")
}
// 调用函数
greet(name: "Alice") // 输出: Hello, Alice!
3. 带返回值的函数
函数可以返回一个值,返回值的类型在函数定义时指定。
swift
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
// 调用函数
展开全文let sum = add(3, 4)
print(sum) // 输出: 7
说明:
_ 表示参数的外部参数名被省略,调用时不需要显式指定参数名。
如果没有 _,则参数名在调用时也需要提供,例如 add(a: 3, b: 4)。
4. 带外部参数名的函数
外部参数名可以让函数调用更加语义化。
swift
func multiply(firstNumber a: Int, bySecondNumber b: Int) -> Int {
return a * b
}
// 调用函数
let product = multiply(firstNumber: 5, bySecondNumber: 6)
print(product) // 输出: 30
5. 带默认参数值的函数
可以为参数提供默认值,这样在调用函数时可以省略这些参数。
swift
func greet(name: String, message: String = "How are you?") {
print("\(name), \(message)")
}
// 调用函数
greet(name: "Bob") // 输出: Bob, How are you?
greet(name: "Bob", message: "Good morning!") // 输出: Bob, Good morning!
6. 可变参数的函数
函数可以接受可变数量的参数,使用 ... 表示。
swift
func sumOfNumbers(_ numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
// 调用函数
let total = sumOfNumbers(1, 2, 3, 4, 5)
print(total) // 输出: 15
7. 返回元组的函数
函数可以返回多个值,通过返回元组实现。
swift
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, average: Double) {
let sortedScores = scores.sorted()
let min = sortedScores.first ?? 0
let max = sortedScores.last ?? 0
let average = scores.reduce(0, +) / Double(scores.count)
return (min, max, average)
}
// 调用函数
let stats = calculateStatistics(scores: [85, 92, 78, 90, 88])
print("Min: \(stats.min), Max: \(stats.max), Average: \(stats.average)")
// 输出: Min: 78, Max: 92, Average: 86.6
8. 嵌套函数
函数可以嵌套在其他函数内部,内部函数可以访问外部函数的变量。
swift
func outerFunction() {
let outerVariable = "I am outside"
func innerFunction() {
print(outerVariable) // 可以访问外部函数的变量
}
innerFunction()
}
// 调用函数
outerFunction() // 输出: I am outside
9. 函数作为返回值
函数可以返回另一个函数。
swift
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
// 调用函数
let incrementByTen = makeIncrementer(forIncrement: 10)
print(incrementByTen()) // 输出: 10
print(incrementByTen()) // 输出: 20
10. 函数作为参数
函数可以作为参数传递给另一个函数。
swift
func printResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
// 调用函数
printResult(add, 3, 4) // 输出: Result: 7
printResult({ $0 * $1 }, 3, 4) // 使用闭包,输出: Result: 12
总结
函数定义:使用 func 关键字。
参数:可以指定名称、类型和默认值。
返回值:可以返回单个值、元组,甚至没有返回值(Void)。
高级特性:支持可变参数、嵌套函数、函数作为返回值或参数。
通过这些特性,Swift 的函数非常灵活,可以满足各种编程需求。