Swift 函数
封面图
•
2025-10-18
•
Swift
5
0
0
0
在 **Swift** 中,函数(function)是一种用于执行特定任务的代码块。你可以定义自己的函数,并在程序中调用它们。 --- ## 📌 Swift 函数的基本语法: ```swift func functionName(parameters: Type) -> ReturnType { // 函数体 return value } ``` ### 示例:一个简单的函数 ```swift func greet(name: String) -> String { return "Hello, $name)" } ``` 调用这个函数: ```swift let greeting = greet(name: "Alice") print(greeting) // 输出: Hello, Alice ``` --- ## ✅ 函数参数和返回值 ### 1. 没有返回值的函数 ```swift func sayHello() { print("Hello!") } ``` 调用: ```swift sayHello() // 输出: Hello! ``` ### 2. 多个参数的函数 ```swift func add(a: Int, b: Int) -> Int { return a + b } ``` 调用: ```swift let result = add(a: 3, b: 5) print(result) // 输出: 8 ``` ### 3. 默认参数值 ```swift func greet(name: String = "Guest") { print("Hello, $name)") } ``` 调用: ```swift greet() // 输出: Hello, Guest greet(name: "Bob") // 输出: Hello, Bob ``` ### 4. 可变参数(varargs) ```swift func sum(numbers: Int...) -> Int { return numbers.reduce(0, +) } ``` 调用: ```swift let total = sum(numbers: 1, 2, 3, 4) print(total) // 输出: 10 ``` ### 5. 使用外部参数名 ```swift func greet(person name: String) { print("Hello, $name)") } ``` 调用时需要使用外部参数名: ```swift greet(person: "Charlie") ``` --- ## 🧠 闭包(Closure)与函数的关系 在 Swift 中,函数其实就是一种特殊的闭包。你可以将函数赋值给变量或作为参数传递给其他函数。 例如: ```swift let myFunction: (Int, Int) -> Int = add let result = myFunction(3, 5) // 结果是 8 ``` --- ## ✨ 常见函数类型 | 类型 | 示例 | |------|------| | 无参数、无返回值 | `func doSomething()` | | 有参数、无返回值 | `func printMessage(message: String)` | | 有参数、有返回值 | `func add(a: Int, b: Int) -> Int` | | 可变参数 | `func sum(numbers: Int...) -> Int` | | 外部参数名 | `func greet(person name: String)` | --- 如果你有具体的函数需求,比如“如何定义带可选参数的函数”、“如何处理错误”、“函数式编程中的高阶函数”等,我也可以进一步讲解!你想了解哪方面?
上一篇:
Swift 字典
标题录入,一次不能超过6条
返回顶部
留言
留言
评论