Swift 3.0 (二)
一:函数
1.1无参数无返回值的简单函数
1 func sendMessage(){ 2 3 let message = "Hey, Guys!" 4 5 print(message) 6 7 } 8 9 sendMessage()
1.2带一个参数的、无返回值得函数
1 func sendMessage(shouting : Bool){ //shouting叫做参数label 2 var message = "Hello" 3 4 if(shouting){ 5 message = message.uppercased() 6 } 7 8 print(message) 9 } 10 11 sendMessage(shouting : true) //调用函数是除了参数值外还要带有参数label,官方的解析是增加代码的可读性
//如果没有label函数使用者会误以为这个Bool参数代码是否发送的意思
想要在调用函数时不带参数label话,定义函数时在参数label前添加一个 "_" , (_ shouting : Bool),
完整的函数定义是:func sendMessage(_ shouting : Bool), 这样在调用函数时不需要也不能传入label。
另外一个参数可以有两个label,第一个是供调用时使用, 一个是供函数体内使用,例如
1 func sendMessage(loud shouting : Bool){ 2 var message = "Hello" 3 4 if(shouting){ 5 message = message.uppercased() 6 } 7 8 print(message) 9 } 10 11 sendMessage(loud : true) //OK 12 13 sendMessage(shouting: true) //Error shouting只能在函数体内使用