返回值的类型是可选元组,当输入的数组是空数组时,将会返回nil。
4. 函数参数标签和参数名字
a. 参数标签的用法
每一个函数参数都有一个参数标签和一个参数名字。
参数标签是当调用这个函数的时候使用,参数的名字是在实现函数的时候使用。
参数标签默认是参数的名字。
func someFunction(label1 firstParameterName: Int, label2 secondParameterName: Int) {
// In the function body, firstParameterName and secondParameterName
// refer to the argument valuesfor the first and second parameters.
}
someFunction(label1: 1, label2: 2)
默认标签:
func someFunction(firstParameterName: Int, secondParameterName: Int) {
// In the function body, firstParameterName and secondParameterName
// refer to the argument valuesfor the first and second parameters.
}
someFunction(1, secondParameterName: 2)
注:在Swift 3之前,当使用默认标签的时候,调用函数的时候,第一个参数不能带标签,如下:
someFunction(firstParameterName:1, secondParameterName: 2)
将会出错。但是,在Swift 3中将不会有这样的错误。
b. 删除参数标签
如果你不想使用参数标签,用下划线“_”代替标签:
func someFunction(firstParameterName: Int, _ secondParameterName: Int) {
// In the function body, firstParameterName and secondParameterName
// refer to the argument valuesfor the first and second parameters.
}
someFunction(1, 2)
5. 默认参数值
func someFunction(parameterWithDefault: Int = 12) {
// In the function body, ifno arguments are passed to the function// call, the value of parameterWithDefault is12.
}
someFunction(6) // parameterWithDefault is6
someFunction() // parameterWithDefault is12”
func sum(numbers: Double...) -> Double{
vars: Double = 0;
for value in numbers {
s += value
}
return s
}
let s = sum(1,2,4,4.5)
print("the sum of 1,2,4,4.5 is: \(s)")
let s1 = sum(1,2,4,4.5,10.4, 12.2)
print("the sum of 1,2,4,4.5,10.4, 12.2 is: \(s1)")
输出结果
the sum of 1,2,4,4.5 is: 11.5
the sum of 1,2,4,4.5,10.4, 12.2 is: 34.1
Program ended with exit code: 0
7. In-Out 参数
函数参数默认是常量,所以在函数体中修改函数参数的值将会导致运行时错误。
但是如果你想修改函数参数的值而且当函数调用结束后修改后的值还能维持不变,那就使用in-out 参数。
调用函数时,你只能传递变量作为参数,而不能传递传递常量和字面量作为参数,而且需要在变量前面加“&”符号。
注:in-out参数不能有默认值,而且可变参数不能是inout类型参数。
func swapTwoValue(inout a: Int, inout _ b: Int){
let temp = aa = b
b = temp
}
var a = 3;
var b = 4;
swapTwoValue(&a, &b)
print("a = \(a); b = \(b)")
结果为:
a = 4; b = 3
Program ended with exit code: 0
在Swift 3 中,inout关键字的位置是位于冒号之后,参数类型之前,如下:
func swapTwoValue(_ a: inout Int, _ b: inout Int){
let temp = aa = b
b = temp
}