函数的声明和调用
函数例子:
fun sayHello(personName : String) -> String{
let greeting = "hello," + personName + "!"
return greeting
}
函数的参数和返回值
多输入参数
fun halfOpenRangeLength(Start : Int, end : Int) -> Int{
return end - start
}
无参数
fun sayHelloWorld() -> String {
return "hello,world"
}
没有返回值得的函数
func sayGoodBye(personName : String){
print("GoodBye,\(personName)")
}
多返回值函数
可以使用一个元组作为函数的返回类型返回一个有多个值组成的复合返回值。
fun count(string : String) -> (vowels : Int , consonants : Int , others : Int){
var vowels = 0 , consonants = 0, others = 0
for character in string {
switch String(character).lowecaseString{
case "a","e","i","o","u"
++vowles
case "b","x","y","z'
++consonants
default:
++others
}
return (vowels,consonants,others)
}
}