Swift从0开始学习 函数和闭包 day2

一、函数
1.1函数定义

使用 func 来声明一个函数,使用名字和参数来调用函数。使用 -> 来指定函数返回值的类型。

示例:拼接字符串

Swift 复制代码
//有参数和返回值的函数
func append1(name : String, description : String) -> String {
    return "\(name) is \(description)"
}

//调用
append1(name: "Tony", description: "good")

运行结果:

默认情况下,函数会使用默认的参数名称作为参数标签,如果需要自定义参数标签,示例如下

"youName"和"youHabby"是自定义的标签

Swift 复制代码
//在参数名称前自定义参数标签
func CustomParameterLabels(youName name : String, youHabby habby : String) -> String {
    return "\(name)'s hobbies is \(habby).(Custom parameter labels)"
}

CustomParameterLabels(youName: "Tony", youHabby: "cutting hair")

运行结果:

如果不想使用传输标签,可以使用"_"来实现

Swift 复制代码
//不使用参数标签,可以使用"_"来表示
func NoneParameter(_ name : String, habby : String) -> String {
    return "\(name)'s hobbies is \(habby).(Parameter-free labels)"
}

NoneParameter("Tony", habby: "cutting hair")

运行结果:

如果函数需要返回多个值,可以使用元组来实现。示例

这里返回多个值没有参数标签

Swift 复制代码
func getMultipleValues() -> (Int, String, Bool) {
    return (42, "Hello", true)
}

// 调用示例
let result = getMultipleValues()

运行结果:

如果需要返回的多个值是有标签的,参考如下:

Swift 复制代码
//返回带参数标签的多个值
func getMultipleValues() -> (minScore : Int, maxScore : Int, totalScore : Int) {
    return (42, 99, 141)
}

// 调用示例
let result = getMultipleValues()

print(result.0)
print(result.minScore)

运行结果:

1.2函数嵌套,复合使用

函数内可以继续嵌套函数来处理较长或者复杂的实现。示例;

Swift 复制代码
//整数转字符串
func IntToString(score : Int) -> String {
    //加多十分
    func toString(score : Int) -> Int{
        var score = score + 10
        return score
    }
    var newScore = toString(score: score)
    return "\(newScore)"
}

IntToString(score: 90)

运行结果:

函数也可以当做返回值,使用示例如下:

Swift 复制代码
func addScore() -> ((Int) -> Int) {
    //加多十分
    func addTenScore(score : Int) -> Int{
        return score + 10
    }
    return addTenScore
}

//调用,返回一个函数
var myFunc = addScore()
//调用这个函数
myFunc(80)

函数也可以作为参数传入。如下

Swift 复制代码
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)
1.3闭包

闭包(Closure)是一块自包含的代码,可以在代码中被传递和使用。闭包可以捕获和存储其所在上下文中的变量和常量的引用

闭包的基础语法:

​​​​​​​

Swift 复制代码
// 闭包的基本形式
{ (parameters) -> returnType in
    // 闭包的实现代码
}
  • parameters 是闭包的输入参数(可以为空)。
  • returnType 是闭包的返回值类型(可以省略,Swift 会推断)。
  • in 关键字分隔了闭包的参数和实现代码。

简单闭包的实现:

Swift 复制代码
// 一个简单的闭包,接收两个整数,返回它们的和
let add: (Int, Int) -> Int = { (a, b) in
    return a + b
}

// 使用闭包
let result = add(3, 5)
print(result)  // 输出 8

闭包捕获值

Swift 复制代码
func makeIncrementer(incrementAmount: Int) -> () -> Int {
    var total = 0
    let incrementer: () -> Int = {
        total += incrementAmount  // 捕获 incrementAmount 和 total
        return total
    }
    return incrementer
}

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

在这个例子中,incrementByTwo 捕获了 incrementAmounttotal,每次调用 incrementByTwo() 时,total 都会增加 2。

闭包作为函数参数

闭包常常用作函数的参数,特别是在处理异步操作、回调等情况时,在网络请求中用的最多。例如:

​​​​​​​

Swift 复制代码
func fetchData(completion: @escaping (String) -> Void) {
    // 模拟网络请求
    DispatchQueue.global().async {
        // 模拟延迟
        Thread.sleep(forTimeInterval: 2)
        DispatchQueue.main.async {
            completion("数据加载完成")
        }
    }
}

fetchData { data in
    print(data)  // 输出 "数据加载完成"
}

使用闭包时管理好对外部对象的引用.

相关推荐
2501_916013749 小时前
iOS混淆工具有哪些?跨平台 App 混淆与保护的实用方案
android·ios·小程序·https·uni-app·iphone·webview
2501_915909069 小时前
iOS 文件管理实战指南,用户文件、安全访问与开发调试方案
android·ios·小程序·https·uni-app·iphone·webview
Digitally10 小时前
3 种简单方法备份 iPhone 上的短信 [2025]
ios·iphone
归辞...11 小时前
「iOS」————NSOperation
macos·ios·cocoa
叽哥21 小时前
flutter学习第 8 节:路由与导航
android·flutter·ios
叽哥21 小时前
flutter学习第 7 节:StatefulWidget 与状态管理基础
android·flutter·ios
DogDaoDao1 天前
深入理解VideoToolbox:iOS/macOS视频硬编解码实战指南
macos·ios·音视频·实时音视频·视频编解码·videotoolbox·硬编码
Andy_GF2 天前
纯血鸿蒙HarmonyOS Next 远程测试包分发
前端·ios·harmonyos
归辞...2 天前
「iOS」————自动释放池底层原理
macos·ios·cocoa
2501_916007472 天前
Charles中文版抓包工具使用指南 提高API调试和网络优化效率
android·ios·小程序·https·uni-app·iphone·webview