Swift笔记:函数
2016-04-15 10:28
399 查看
函数
以 func 作为前缀。 ->(一个连字符后跟一个右尖括号)后跟返回类型的名称的方式来表示函数返回值。函数名后面()为函数参数。
无参函数(Functions Without Parameters)
多参数函数 (Functions With Multiple Parameters)
无返回值函数(Functions Without Return Values)
多重返回值函数(Functions with Multiple Return Values)
函数类型(Function Types)
每个函数都有种特定的函数类型,由函数的参数类型和返回类型组成。
这两个函数的类型是 (Int, Int) -> Int,可以解读为“这个函数类型有两个 Int 型的参数并返回一个 Int 型的值。”。
这个函数的类型是:() -> Void,或者叫“没有参数,并返回 Void 类型的函数”。
//声明函数 func sayhello(person:String) -> String { let str = "hello," + person return str } //调用函数 print(sayhello("locay")) //hello,locay
以 func 作为前缀。 ->(一个连字符后跟一个右尖括号)后跟返回类型的名称的方式来表示函数返回值。函数名后面()为函数参数。
无参函数(Functions Without Parameters)
func sayHelloWorld() -> String { return "hello, world" } print(sayHelloWorld()) // prints "hello, world"
多参数函数 (Functions With Multiple Parameters)
func sayHello(personName: String, alreadyGreeted: Bool) -> String { if alreadyGreeted { return sayHelloAgain(personName) } else { return sayHello(personName) } } print(sayHello("Tim", alreadyGreeted: true)) // prints "Hello again, Tim!"
无返回值函数(Functions Without Return Values)
func sayGoodbye(personName: String) { print("Goodbye, \(personName)!") } sayGoodbye("Dave") // prints "Goodbye, Dave!"
多重返回值函数(Functions with Multiple Return Values)
func minMax(array: [Int]) -> (min: Int, max: Int) { var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) }
函数类型(Function Types)
每个函数都有种特定的函数类型,由函数的参数类型和返回类型组成。
func addTwoInts(a: Int, _ b: Int) -> Int { return a + b } func multiplyTwoInts(a: Int, _ b: Int) -> Int { return a * b }
这两个函数的类型是 (Int, Int) -> Int,可以解读为“这个函数类型有两个 Int 型的参数并返回一个 Int 型的值。”。
func printHelloWorld() { print("hello, world") }
这个函数的类型是:() -> Void,或者叫“没有参数,并返回 Void 类型的函数”。
相关文章推荐
- Apple Swift学习教程
- 介绍 Fedora 上的 Swift
- Mootools 1.2教程 函数
- autoit InputBox 函数
- 文件遍历排序函数
- Oracle 函数大全[字符串函数,数学函数,日期函数]第1/4页
- ASP下经常用的字符串等函数参考资料
- PostgreSQL教程(五):函数和操作符详解(1)
- DOS批处理 函数定义与用法
- asp Chr 函数 数字转字母的方法
- Lua中的函数精讲笔记
- Lua中的闭合函数、非全局函数与函数的尾调用详解
- Lua中调用C++函数示例
- Lua实现split函数
- Lua常用时间函数使用实例
- Lua函数与字符串处理简明总结
- Lua学习笔记之表和函数
- Lua中实现sleep函数功能的4种方法
- Lua函数用法研究