码迷,mamicode.com
首页 > 编程语言 > 详细

Swift函数

时间:2017-07-25 21:22:13      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:character   step   rds   使用   line   oda   www   交流群   调用   

函数定义

 

使用 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



Swift函数

标签:character   step   rds   使用   line   oda   www   交流群   调用   

原文地址:http://www.cnblogs.com/gccbuaa/p/7236143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!