Swift 开发教程系列 - 第4章:函数与闭包

在 Swift 中,函数和闭包是代码组织和复用的基础。通过定义函数,我们可以将代码封装成可重用的模块。闭包则是一种功能强大的匿名函数表达式,适用于高阶函数和回调操作。

4.1 函数的定义与调用

函数是具有名称的代码块,可以被多次调用。Swift 中的函数使用 func 关键字定义,函数可以接收参数并返回结果。

swift 复制代码
//基础语法
func 函数名(参数1: 类型, 参数2: 类型, ...) -> 返回类型 {
    // 函数体
    return 返回值
}

//示例代码
func greet(name: String) -> String {
    return "Hello, \(name)!"
}

let message = greet(name: "Alice")
print(message)  // 输出:"Hello, Alice!"

在上例中,greet 函数接受一个 String 类型的参数,并返回一个 String 类型的值。

4.2 无返回值的函数

如果函数不需要返回值,可以省略返回类型,或直接用 Void 或 () 表示无返回值。

swift 复制代码
func sayHello() {
    print("Hello, World!")
}

sayHello()  // 输出:"Hello, World!"

4.3 多参数与默认参数值

函数可以接受多个参数,并且可以为参数设置默认值,调用时可以省略带有默认值的参数。

swift 复制代码
func introduce(name: String, age: Int = 18) {
    print("My name is \(name) and I am \(age) years old.")
}

introduce(name: "Bob")            // 输出:"My name is Bob and I am 18 years old."
introduce(name: "Bob", age: 25)    // 输出:"My name is Bob and I am 25 years old."

4.4 函数参数标签

在 Swift 中,函数参数可以有外部参数标签,这使得函数的调用更具可读性。外部参数标签在函数名和参数名之间使用,不影响函数体中的参数名称。

swift 复制代码
func multiply(num1 firstNumber: Int, num2 secondNumber: Int) -> Int {
    return firstNumber * secondNumber
}

let result = multiply(num1: 3, num2: 4)  // 输出:12

4.5 闭包的定义与使用

闭包是可以捕获并存储其上下文中的常量和变量的自包含代码块。闭包的语法非常简洁,因此常用于回调或高阶函数中。

swift 复制代码
//基础语法
{ (参数1: 类型, 参数2: 类型, ...) -> 返回类型 in
    // 闭包体
    return 返回值
}

//示例代码
let square = { (number: Int) -> Int in
    return number * number
}

let result = square(5)
print(result)  // 输出:25

4.6 闭包的简写语法

Swift 允许闭包采用简写参数名(如 0、1)和省略返回关键字,从而使代码更简洁。通常在闭包作为参数传递时非常有用。

swift 复制代码
let numbers = [1, 2, 3, 4, 5]

// 使用闭包对数组进行映射操作
let squares = numbers.map { $0 * $0 }
print(squares)  // 输出:[1, 4, 9, 16, 25]

4.7 闭包的捕获值

闭包可以捕获并存储定义闭包的上下文中的变量和常量,即使这些变量和常量的作用域已经销毁,闭包仍可以访问它们。

swift 复制代码
//示例代码
func makeIncrementer(increment amount: Int) -> () -> Int {
    var total = 0
    return {
        total += amount
        return total
    }
}

let incrementByTwo = makeIncrementer(increment: 2)
print(incrementByTwo())  // 输出:2
print(incrementByTwo())  // 输出:4
print(incrementByTwo())  // 输出:6

在此例中,返回的闭包捕获了 total 变量,每次调用时都可以访问并更新 total 的值。

通过本章内容,你已掌握 Swift 中的函数定义和闭包使用。下一章我们将讨论 Swift 的集合类型,包括数组、字典和集合的用法。

相关推荐
YungFan26 分钟前
iOS26适配指南之通知
ios·swift
木叶丸1 小时前
跨平台方案该如何选择?
android·前端·ios
我唔知啊2 小时前
OC底层原理二:OC对象的分类(实例对象、类对象、元类对象)
ios·objective-c
泓博3 小时前
KMP(Kotlin Multiplatform)改造(Android/iOS)老项目
android·ios·kotlin
Digitally3 小时前
如何将信息从 iPhone 同步到Mac(完整步骤和示意图)
macos·ios·iphone
大猫会长3 小时前
使用Mac自带的图像捕捉导出 iPhone 相册
ios·iphone
大熊猫侯佩10 天前
消失的它:摆脱 SwiftUI 中“嵌入视图数量不能超过 10 个”限制的秘密
swiftui·swift·apple
大熊猫侯佩10 天前
Swift 抛砖引玉:从数组访问越界想到的“可抛出错误”属性
swift·apple
大熊猫侯佩10 天前
ruby、Python 以及 Swift 语言关于 “Finally” 实现的趣谈
python·ruby·swift
二流小码农10 天前
鸿蒙开发:基于node脚本实现组件化运行
android·ios·harmonyos