函数
苹果官方指南
苹果官方指南翻译
函数名
描述函数功能,调用函数时使用。定义和调用函数
func greetAgain(person: String) -> String { return "Hello again, " + person + "!"}print(greetAgain(person: "Anna"))// Prints "Hello again, Anna!"
func 关键字,greetAgain 函数名,person 参数标签,String 参数类型,-> String 返回值及其类型, {} 函数功能代码,"Anna" 实际参数
函数形式参数和返回值
无形式参数的函数
func sayHelloWorld() -> String { return "hello, world"}print(sayHelloWorld())// prints "hello, world"
多形式参数的函数
func greet(person: String, alreadyGreeted: Bool) -> String { if alreadyGreeted { return greetAgain(person: person) } else { return greet(person: person) }}print(greet(person: "Tim", alreadyGreeted: true))// Prints "Hello again, Tim!"
无返回值的函数
func printAndCount(string: String) -> Int { print(string) return string.characters.count}func printWithoutCounting(string: String) { let _ = printAndCount(string: string)}printAndCount(string: "hello, world")// prints "hello, world" and returns a value of 12printWithoutCounting(string: "hello, world")// prints "hello, world" but does not return a value
严格来说,无返回值函数返回了特殊值Void,如有返回值,需要处理返回值,不然函数出错。多返回值的函数
func minMax(array: [Int]) -> (min: Int, max: Int) { var currentMin = array[0] var currentMax = array[0] for value in array[1..
currentMax { currentMax = value } } return (currentMin, currentMax)}let bounds = minMax(array: [8, -6, 2, 109, 3, 71])print("min is \(bounds.min) and max is \(bounds.max)")// Prints "min is -6 and max is 109" 可选元组的返回类型
func minMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { return nil } var currentMin = array[0] var currentMax = array[0] for value in array[1..
currentMax { currentMax = value } } return (currentMin, currentMax)} 函数实际参数标签和形式参数名
指定实际参数标签
func greet(person: String, from hometown: String) -> String { return "Hello \(person)! Glad you could visit from \(hometown)."}print(greet(person: "Bill", from: "Cupertino"))// Prints "Hello Bill! Glad you could visit from Cupertino."
省略实际参数标枪
func someFunction(_ firstParameterName: Int, secondParameterName: Int) { // In the function body, firstParameterName and secondParameterName // refer to the argument values for the first and second parameters.}someFunction(1, secondParameterName: 2)
利用下划线( _ )来为这个形式参数代替显式的实际参数标签默认形式参数值
func someFunction(parameterWithDefault: Int = 12) { // In the function body, if no arguments are passed to the function // call, the value of parameterWithDefault is 12.}someFunction(parameterWithDefault: 6) // parameterWithDefault is 6someFunction() // parameterWithDefault is 12
可变的形式参数
func arithmeticMean(_ 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 numbersarithmeticMean(3, 8.25, 18.75)// returns 10.0, which is the arithmetic mean of these three numbers
形式参数的类型名称后边插入三个点符号( ...)来书写可变形式参数输入输出形式参数
func swapTwoInts(_ a: inout Int, _ b: inout Int) { let temporaryA = a a = b b = temporaryA}var someInt = 3var anotherInt = 107swapTwoInts(&someInt, &anotherInt)print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")// prints "someInt is now 107, and anotherInt is now 3"
在将变量作为实际参数传递给输入输出形式参数的时候,直接在它前边添加一个和符合 ( &) 来明确可以被函数修改。
函数类型
使用函数类型
func addTwoInts(_ a: Int, _ b: Int) -> Int { return a + b}func multiplyTwoInts(_ a: Int, _ b: Int) -> Int { return a * b}var mathFunction: (Int, Int) -> Int = addTwoIntsprint("Result: \(mathFunction(2, 3))")// prints "Result: 5"mathFunction = multiplyTwoIntsprint("Result: \(mathFunction(2, 3))")// prints "Result: 6"
函数类型作为形式参数类型
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { print("Result: \(mathFunction(a, b))")}printMathResult(addTwoInts, 3, 5)// Prints "Result: 8"
函数类型作为返回类型
func stepForward(_ input: Int) -> Int { return input + 1}func stepBackward(_ input: Int) -> Int { return input - 1}func chooseStepFunction(backwards: Bool) -> (Int) -> Int { return backwards ? stepBackward : stepForward}var currentValue = 3let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)// moveNearerToZero now refers to the stepBackward() functionprint("Counting to zero:")// Counting to zero:while currentValue != 0 { print("\(currentValue)... ") currentValue = moveNearerToZero(currentValue)}print("zero!")// 3...// 2...// 1...// zero!
内嵌函数
func chooseStepFunction(backward: Bool) -> (Int) -> Int { func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } return backward ? stepBackward : stepForward}var currentValue = -4let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)// moveNearerToZero now refers to the nested stepForward() functionwhile currentValue != 0 { print("\(currentValue)... ") currentValue = moveNearerToZero(currentValue)}print("zero!")// -4...// -3...// -2...// -1...// zero!