- function names describe function functions, which are used when calling functions.
- Defining and calling Functions
func greetAgain(person: String) -> String { return "Hello again, " + person + "!"}print(greetAgain(person: "Anna"))// Prints "Hello again, Anna!"
Func keyword, greetagain function name, person parameter label, string parameter type,-> string return value and its type, {} function function code, "Anna" actual argument
function form parameters and return values
- Functions with no formal parameters
func sayHelloWorld() -> String { return "hello, world"}print(sayHelloWorld())// prints "hello, world"
- Functions of multi-form parameters
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!"
- function with no return value
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
Strictly speaking, no return value function returns a special value void, and if there is a return value, the return value needs to be processed or the function is faulted.
- Functions with multiple return values
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(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"
- return type of an optional tuple
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..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax)}
function actual parameter label and formal parameter name
- Specify the actual parameter label
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."
- Omit actual parameter Javelin
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)
Use an underscore (_) to replace the explicit actual parameter label for this form parameter
- Default form parameter values
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
- Variable formal parameters
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
The type name of the formal parameter is inserted behind the three dot symbol (...). ) to write variable form parameters
- Input and output form parameters
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"
function type
- Using function types
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"
- function type as formal parameter type
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { print("Result: \(mathFunction(a, b))")}printMathResult(addTwoInts, 3, 5)// Prints "Result: 8"
- function type as return type
func stepforward (_ Input:int), Int {return input + 1}func Stepbackward (_ Input:int)-& Gt int {return input-1}func choosestepfunction (backwards:bool)-(int), int {return backwards? stepbackw Ard:stepforward}var CurrentValue = 3let Movenearertozero = choosestepfunction (Backward:currentvalue > 0)//moveNeare Rtozero 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!
- inline functions
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!