swift函数

来源:互联网 发布:上海程序员培训机构 编辑:程序博客网 时间:2024/05/25 05:37

函数的声明和调用

函数例子:

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)

}

}


0 0