funcminMax(array: [Int]) -> (min: Int, max: Int) { var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } elseif value > currentMax { currentMax = value } } return (currentMin, currentMax) }
funcminMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { returnnil } var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } elseif value > currentMax { currentMax = value } } return (currentMin, currentMax) }
funcsomeFunction(firstParameterName: Int, secondParameterName: Int) { // function body goes here // firstParameterName and secondParameterName refer to // the argument values for the first and second parameters } someFunction(firstParameterName: 1, secondParameterName: 2)
指定外部参数名
1 2 3 4
funcsomeFunction(externalParameterNamelocalParameterName: Int) { // function body goes here, and can use localParameterName // to refer to the argument value for that parameter }
1 2 3 4 5
funcsayHello(toperson: String, andanotherPerson: String) -> String { return"Hello \(person) and \(anotherPerson)!" } print(sayHello(to: "Bill", and: "Ted")) // prints "Hello Bill and Ted!"
funcsomeFunction(firstParameterName: Int, _secondParameterName: Int) { // function body goes here // firstParameterName and secondParameterName refer to // the argument values for the first and second parameters } someFunction(1, 2)
funcsomeFunction(_parameterWithDefault: Int=12) { // function body goes here // if no arguments are passed to the function call, // value of parameterWithDefault is 12 } someFunction(6) // parameterWithDefault is 6 someFunction() // parameterWithDefault is 12
可变参数
1 2 3 4 5 6 7 8 9 10 11
funcarithmeticMean(numbers: Double...) -> Double { var total: Double=0 for number in numbers { total += number } return total /Double(numbers.count) } arithmeticMean(1, 2, 3, 4, 5) // returns 3.0, which is the arithmetic mean of these five numbers arithmeticMean(3, 8.25, 18.75) // returns 10.0, which is the arithmetic mean of these three numbers
注意:一个函数最多只能有一个可变参数。
输入输出参数
1 2 3 4 5
funcswapTwoInts(a:inoutInt, _b:inoutInt) { let temporaryA = a a = b b = temporaryA }
调用参数需要添加&
1 2 3 4 5
var someInt =3 var anotherInt =107 swapTwoInts(&someInt, &anotherInt) print("someInt is now \(someInt), and anotherInt is now \(anotherInt)") // prints "someInt is now 107, and anotherInt is now 3"