14.Swift函数

Swift 函数

在 Swift 中,函数是一种用于执行特定任务或计算特定值的独立代码块。函数可以接受参数并返回一个值,也可以没有参数或返回值。以下是 Swift 中常用的函数操作:

1. 定义函数

可以使用 func 关键字定义函数,指定函数名、参数列表和返回类型(如果有返回值的话)。例如:

swift 复制代码
func greet(person: String) -> String {
   let greeting = "Hello, " + person + "!"
   return greeting
}
2. 调用函数:

可以使用函数名和参数列表来调用函数,并使用返回值(如果有的话)。例如:

swift 复制代码
let message = greet(person: "Alice")
print(message)  // 输出:Hello, Alice!
3. 参数和返回值

函数可以包含零个或多个参数,并且可以返回零个或一个值。参数可以有默认值,也可以使用不定数量的参数。例如:

swift 复制代码
func greet(person: String, from hometown: String = "New York") -> String {
   return "Hello, \(person)! Glad you could visit from \(hometown)."
}
let message1 = greet(person: "Alice")  // 使用默认值
let message2 = greet(person: "Bob", from: "Los Angeles")  // 指定参数值
4. 函数类型

在 Swift 中,函数也是一种类型,可以作为参数传递给其他函数,或作为返回值从函数中返回。例如:

swift 复制代码
func add(_ a: Int, _ b: Int) -> Int {
   return a + b
}
func subtract(_ a: Int, _ b: Int) -> Int {
   return a - b
}
func printResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
   let result = mathFunction(a, b)
   print("Result: \(result)")
}
printResult(add, 5, 3)  // 输出:Result: 8
printResult(subtract, 5, 3)  // 输出:Result: 2
5. 嵌套函数

在 Swift 中,可以在函数内部定义另一个函数,称为嵌套函数。嵌套函数可以访问其外部函数的变量。例如:

swift 复制代码
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
   func stepForward(_ input: Int) -> Int { return input + 1 }
   func stepBackward(_ input: Int) -> Int { return input - 1 }
   return backward ? stepBackward : stepForward
}
let currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
print("Counting to zero:")
// 输出:3 2 1 0
while currentValue != 0 {
   print("\(currentValue)... ")
   currentValue = moveNearerToZero(currentValue)
}

Swift 中的函数功能丰富,支持参数默认值、可变参数、函数类型、嵌套函数等特性,使得函数在编写代码时非常灵活和强大。函数是 Swift 编程的核心之一,用于组织代码、封装逻辑和实现各种功能。

相关推荐
江公望3 小时前
Ubuntu htop命令,10分钟讲清楚
linux·服务器
哎呦,帅小伙哦3 小时前
Linux 时间:从原子钟到 clock_gettime 的每一面
linux·运维·服务器
张小姐的猫4 小时前
【Linux】多线程 —— 线程互斥
linux·运维·服务器·c++
YuanDaima20484 小时前
Linux 进阶运维与 AI 环境实战:进程管理、网络排错与 GPU 监控
linux·运维·服务器·网络·人工智能
lolo大魔王6 小时前
Linux 数据文件处理实战:排序、搜索、压缩、归档一站式详解
linux·运维·服务器
189228048616 小时前
NY382固态MT29F32T08GSLBHL8-24QM:B
大数据·服务器·人工智能·科技·缓存
xhbh6666 小时前
网关端口映射和路由器端口转发有什么区别?配置要点全解析
运维·服务器·网络·智能路由器·端口映射·映射·无痕网关
STDD7 小时前
Soulmask《灵魂面具》 专用服务器搭建教程
运维·服务器·github
半壶清水7 小时前
用P4 Tutorial、BMv2 和 Mininet‌解析网络第一集------模拟环境搭建
运维·服务器·网络·网络协议·tcp/ip
.YYY7 小时前
RHCE--Linux循环执行的例行性任务:crontab从入门到精通
linux·运维·服务器