//1.无参无返回值的函数
func firstFunction(){
print("firstFunction.")
}
firstFunction()
//2.无参有返回值的函数
func secondFunction() -> Int{//返回值为整型
return 123
}
print("sectond value is ",secondFunction())
//3.有参数有返回值的函数
func thirdFunction(firstValue:Int , sectondValue:Int) ->Int {//返回值为整型
return firstValue + sectondValue
}
print("third value is ",thirdFunction(2,sectondValue:2))
//4.有参数有返回值的函数(返回值为元组)
func fourthFunction(firstValue:Int ,secondValue:Int) -> (doubled:Int , quadruple:Int){
return (firstValue*3 , secondValue*5)
}
fourthFunction(2, secondValue:3)
print("fourth value is ",fourthFunction(2,secondValue:6).quadruple)
//fourth value is 30
//4.firstNumber toSecondNumber 为外部名字
num1 num2为内部名字
func addNumbers(firstNumber num1:Int , toSecondNumber num2:Int) ->Int{
return num1+num2
}
addNumbers(firstNumber: 2, toSecondNumber: 3)// =5
//5.其中一个参数为默认值
func multiplyNumbers2 (firstNumber:Int,multiplier:Int =2) ->Int{
return firstNumber*multiplier
}
multiplyNumbers2(2)//=4,可以省略具有默认值的参数
//6.可变参数(若有多个参数时,只有最后一个参数可以是可变参数)
func sumNumbers(numbers:Int...)->Int{
var total = 0
for number in numbers {
total += number
}
return 2
}
sumNumbers(2,2,3)
//将函数用作变量(。。。待学习)P32
//闭包 P34(...待学习)
//引用参数,在函数中的变量为引用变量(此方法用于交换两个参数的值)
func swapValues(inout firstValue:Int , inout secondValue:Int){
let tempValue = firstValue
firstValue = secondValue;
secondValue = tempValue;
}
var swap1 = 2
var swap2 = 3
swapValues(&swap1, secondValue: &swap2)
//swap1 // = 3
//swap2 // = 2