函数是一组用于执行特定任务的独立的代码段,你用一个名字来标识函数,这个名字是用来“调用”函数来执行它的任务。
swift统一函数的语法具有足够的灵活性来表达任何一个简单的不带参数的名称与本地和外部的每个参数的参数名称的复杂objective-c-style C风格的函数方法。参数可以提供默认值,以简化函数调用,并且可以通过在输出参数中,一旦该功能完成了它的执行,它就可以修改传递的变量
swift每一个函数都有一个类型,由形参类型和返回类型组成。你可以使用这种类型的任何其他类型,这使得它很容易将函数作为参数的其他函数,并返回函数的函数。函数还可以用其他函数来封装在嵌套函数作用域内的有用函数。
定义和调用函数
func sayHello(personName: String) -> String { let greeting = "Hello, " + personName + "!" return greeting }
print(sayHello("Anna")) // Prints "Hello, Anna!" print(sayHello("Brian")) // Prints "Hello, Brian!
sayHello是函数的名称,personName是它的参数,类型是String,返回一个String类型的数据,使用->符号来标识函数的返回类型,后面是函数的返回类型。
函数的形参和返回值
函数参数和返回值是非常灵活的。您可以从一个简单的实用程序函数中定义任何一个简单的函数,用一个未命名的参数来定义一个复杂的函数。
无参函数
func sayHelloWorld() -> String { return "hello, world" } print(sayHelloWorld()) // Prints "hello, world
多参函数
func sayHello(personName: String, alreadyGreeted: Bool) -> String { if alreadyGreeted { return sayHelloAgain(personName) } else { return sayHello(personName) } } print(sayHello("Tim", alreadyGreeted: true)) // Prints "Hello again, Tim!
无返回值函数(实际返回void)
func sayGoodbye(personName: String) { print("Goodbye, \(personName)!") } sayGoodbye("Dave") // Prints "Goodbye, Dave!
func printAndCount(stringToPrint: String) -> Int { print(stringToPrint) return stringToPrint.characters.count } func printWithoutCounting(stringToPrint: String) { printAndCount(stringToPrint) } printAndCount("hello, world") // prints "hello, world" and returns a value of 12 printWithoutCounting("hello, world") // prints "hello, world" but does not return a value
多返回值函数
func minMax(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 } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) }
let bounds = minMax([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 someFunction(firstParameterName: Int, secondParameterName: Int) { // function body goes here // firstParameterName and secondParameterName refer to // the argument values for the first and second parameters } someFunction(1, secondParameterName: 2)
默认形参值
您可以在参数类型之后给任何的参数设置一个默认值,如果您设置了默认值,那么就可以在调用该函数时忽略此参数。
func someFunction(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
在函数的参数列表的结尾处设置默认值
可变参数
一个可变的参数接受特定类型的零个或多个值。当函数被调用时,你使用一个可变的参数可以传入不同数量的指定类型的参数,在参数类型名称后面插入...来实现可变参数。函数体的可变参数值被当做一个特定类型的数组来处理。例子如下
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 fi