函数是用来完成特定任务的独立的代码块。你给一个函数起一个合适的名字,用来标识函数做什么,并且当函数需要执行的时候,这个名字会被用于“调用”函数。
Swift 统一的函数语法足够灵活,可以用来表示任何函数,包括从最简单的没有参数名字的 C 风格函数,到复杂的带局部和外部参数名的 Objective-C 风格函数。参数可以提供默认值,以简化函数调用。参数也可以既当做传入参数,也当做传出参数,也就是说,一旦函数执行结束,传入的参数值可以被修改。
在 Swift 中,每个函数都有一种类型,包括函数的参数值类型和返回值类型。你可以把函数类型当做任何其他普通变量类型一样处理,这样就可以更简单地把函数当做别的函数的参数,也可以从其他函数中返回函数。函数的定义可以写在其他函数定义中,这样可以在嵌套函数范围内实现功能封装。
函数定义与调用
func sayHello(personName: String) -> String {
let greeting = "Hello, " + personName + "!"
return greeting
}
print(sayHello("Anna"))
print(sayHello("Brian"))
//简化
func sayHelloAgain(personName: String) -> String {
return "Hello again, " + personName + "!"
}
print(sayHelloAgain("Anna"))
函数的参数和返回值
//函数参数与返回值
//函数参数与返回值在 Swift 中极为灵活。你可以定义任何类型的函数,包括从只带一个未名参数的简单函数到复杂的带有表达性参数名和不同参数选项的复杂函数。
//无参函数
func sayHelloWorld() -> String {
return "hello, world"
}
print(sayHelloWorld())
//多参数函数
func sayHelloToo(personName: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return sayHelloAgain(personName)
} else {
return sayHello(personName)
}
}
print(sayHelloToo("Tim", alreadyGreeted: true))
//无返回值函数
func sayGoodbye(personName: String) {
print("Goodbye, \(personName)!")
}
sayGoodbye("Dave")
func printAndCount(stringToPrint: String) -> Int {
print(stringToPrint)
return stringToPrint.characters.count
}
func printWithoutCounting(stringToPrint: String) {
printAndCount(stringToPrint)
}
printAndCount("hello, world")
printWithoutCounting("hello, world")
//多重返回值函数
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)")
//可选元组返回类型
func minMax1(array: [Int]) -> (Int, Int)? {
var currentMin = array[0]
var currentMax = array[0]
for value in array {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
if let bounds = minMax1([8, -6, 2, 109, 3, 71]) {
print("min is \(bounds.0) and max is \(bounds.1)")
}// 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(externalParameterName localParameterName: Int) {
// function body goes here, and can use localParameterName
// to refer to the argument value for that parameter
}
func sayHello(to person:String, anotherPerson:String) -> String {
return "Hello \(person) and \(anotherPerson)"
}
print(sayHello(to: "Bill", anotherPerson: "Ted"))
//忽略外部参数名
func someFunction(firstParameterName: Int, _ secondParameterName: Int) {
// function body goes here
// firstParameterName and secondParameterName refer to
// the argument values for the first and second paramenters
}
someFunction(1, 2)
//默认参数值
func someFunction(parameterWIthDefault: Int = 12) {
// function body goes here
// if no arguments are passed to the function
// value of parameterWithDefault is 22
}
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)
}
print(arithmeticMean(1, 2, 3, 4, 5))
print(arithmeticMean(3, 8.25, 18.75))
//输入输出参数
func swapTwoInts(inout a: Int, inout b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, b: &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
函数类型
//每个函数都有特定的数据类型,由函数的参数类型和返回值类型组成
func addTwoInts(a: Int, _ b: Int) -> Int{
return a + b
}
func multiplyTwoInts(a: Int, _ b: Int) -> Int {
return a * b
}
func printHelloWorld() {
print("hello, world")
}
//使用函数类型
var mathFunction: (Int, Int) -> Int = addTwoInts
print("Add Result: \(mathFunction(2, 3))")
mathFunction = multiplyTwoInts
print("Mul Result: \(mathFunction(2, 3))")
let anotherMathFunction = addTwoInts //让Swift推断常量的函数类型
//函数类型作为参数类型
func printMatnResult(mathFountion: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMatnResult(addTwoInts, 3, 5) //Result: 15
//函数类型作为返回类型
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards: Bool) -> (Int) -> Int { // (Int) -> Int中 (Int) 是stepForward的参数,Int 是stepForward的返回值,而总体的(Int) -> Int 是chooseStepFunction的返回值
return backwards ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
print("Counting to zero:")
while currentValue != 0 {
print("\(currentValue)...")
currentValue = moveNearerToZero(currentValue)
}
print("zero!")
嵌套函数
func chooseStepFunction1(backwards: Bool) -> (Int) -> (Int) {
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
return backwards ? stepBackward : stepForward
}
currentValue = -4
let moveNearerToZero1 = chooseStepFunction1(currentValue > 0)
while currentValue != 0 {
print("\(currentValue)...")
currentValue = moveNearerToZero1(currentValue)
}
print("zero!")
--EOF--