Swift函数
函数 swift
2023-09-11 14:20:45 时间
函数定义
使用 func 定义一个函数。
调用函数使用他的名字加 上小括号里的參数列表。
使用 -> 分隔參数的名字和 返回值类型。
函数声明:
func greet(name: String, day: String) -> String {
return "Hello \(name),today is \(day)."
}
函数调用:greet("Bob", "Tuesday")
无返回值函数
func sayGoodbye(personName: String) {
println("Goodbye, \(personName)!")
}
sayGoodbye("Tony")
多返回值函数
使用元组类型返回多个值:
func count(string: String) -> (vowels: Int, consonants:Int, others: Int) {
var vowels = 0,consonants = 0, others= 0 for character in string {
switch String(character).lowercaseString {
case "a","e", "i","o", "u":
++vowels
case "b","c", "d","f", "g", "h", "j", "k", "l", "m","n", "p","q", "r","s", "t", "v", "w","x", "y", "z":
++consonants default:
++others
}
}
return (vowels, consonants, others)
}
let total = count("somearbitrary string!")
println("\(total.vowels) 元音 , \(total.consonants) 辅 音")
嵌入函数
函数嵌套: 相当于函数指针
func chooseStepFunction(backwards: Bool) ->(Int) -> Int {
func stepForward(input: Int) -> Int { return input
+ 1 }
func stepBackward(input: Int) -> Int { return input
- 1 }
return backwards ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero =
chooseStepFunction(currentValue> 0)
while currentValue != 0{
println("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
Swift交流讨论论坛论坛:http://www.cocoagame.net
欢迎增加Swift技术交流群:362298485
相关文章
- [C++] 用Xcode来写C++程序[4] 函数
- 蓝桥杯 算法提高 11-1实现strcmp函数 (JAVA方法)
- 阿里云函数计算 FC 助力高德 RTA 广告投放系统架构升级
- 《从零开始学Swift》学习笔记(Day 40)——析构函数
- 《从零开始学Swift》学习笔记(Day 19)——函数参数传递
- 《从零开始学Swift》学习笔记(Day 7)——Swift 2.0中的print函数几种重载形式
- 如何使用Pythonapi函数写股票策略
- Python语言学习之字母A开头函数使用集锦:assert用法之详细攻略
- Swift高速入门之函数
- np.mean()函数 、 np.std() 函数、np.var() 函数
- Swift 1.1语言第7章 函数和闭包
- pytest接口自动化测试框架 | 使用函数返回值的形式传入参数值
- C++虚析构函数
- Windows API一日一练(25)CreateSolidBrush函数
- Windows API一日一练(48)PostThreadMessage函数
- Go 函数 使用函数的正确姿势