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)  // 输出 "数据加载完成"
}

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

相关推荐
幸福回头21 小时前
ms-swift 代码推理数据集
llm·swift
若水无华1 天前
fiddler 配置ios手机代理调试
ios·智能手机·fiddler
不二狗1 天前
每日算法 -【Swift 算法】Two Sum 问题:从暴力解法到最优解法的演进
开发语言·算法·swift
Aress"1 天前
【ios越狱包安装失败?uniapp导出ipa文件如何安装到苹果手机】苹果IOS直接安装IPA文件
ios·uni-app·ipa安装
Jouzzy2 天前
【iOS安全】Dopamine越狱 iPhone X iOS 16.6 (20G75) | 解决Jailbreak failed with error
安全·ios·iphone
瓜子三百克2 天前
采用sherpa-onnx 实现 ios语音唤起的调研
macos·ios·cocoa
左钦杨2 天前
IOS CSS3 right transformX 动画卡顿 回弹
前端·ios·css3
努力成为包租婆2 天前
SDK does not contain ‘libarclite‘ at the path
ios
安和昂3 天前
【iOS】Tagged Pointer
macos·ios·cocoa
I烟雨云渊T3 天前
iOS 阅后即焚功能的实现
macos·ios·cocoa