首页 > 代码库 > Swift函数
Swift函数
函数定义
使用 func 定义一个函数。调用函数使用他的名字加 上小括号中的参数列表。使用 -> 分隔参数的名字和 返回值类型。
函数声明:
[html] view plaincopy
- <span style="font-size:14px;">func greet(name: String, day: String) -> String {
- return "Hello \(name),today is \(day)."
- } </span>
函数调用:greet("Bob", "Tuesday")
无返回值函数
[html] view plaincopy
- <span style="font-size:14px;">func sayGoodbye(personName: String) {
- println("Goodbye, \(personName)!")
- }
- sayGoodbye("Tony")</span>
多返回值函数
使用元组类型返回多个值:
[html] view plaincopy
- <span style="font-size:14px;">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) 辅 音")</span>
嵌入函数
函数嵌套: 相当于函数指针
[html] view plaincopy
- <span style="font-size:14px;">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)
- }</span>
Swift交流讨论论坛论坛:http://www.cocoagame.net
欢迎加入Swift技术交流群:362298485
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。