Chapter 5: Functions

大綱

Function basics

// Function parameters
func printMultipleOf(multiplier: Int, and value: Int) {
  print("\(multiplier) * \(value) = \(multiplier * value)")
}
printMultipleOf(multiplier: 4, and: 2)

func printMultipleOf(_ multiplier: Int, and value: Int) {
  print("\(multiplier) * \(value) = \(multiplier * value)")
}
printMultipleOf(4, and: 2)

func printMultipleOf(_ multiplier: Int, _ value: Int) {
  print("\(multiplier) * \(value) = \(multiplier * value)")
}
printMultipleOf(4, 2)
  • Whenever you call a function, it should always be clear which function you’re calling. This is usually achieved through a difference in the parameter list:

    • A different number of parameters.

    • Different parameter types.

    • Different external parameter names, such as the case with printMultipleOf.

  • Only use overloading for functions that are related and similar in behavior. When only the return type is overloaded, as in the above example, you loose type inference and so is not recommended.

Functions as variables

Key points

  • You use a function to define a task that you can execute as many times as you like without having to write the code multiple times.

  • Functions can take zero or more parameters and optionally return a value.

  • You can add an external name to a function parameter to change the label you use in a function call, or you can use an underscore to denote no label.

  • Parameters are passed as constants, unless you mark them as inout, in which case they are copied-in and copied-out.

  • Functions can have the same name with different parameters. This is called overloading.

  • Functions can have a special Never return type to inform Swift that this function will never exit.

  • You can assign functions to variables and pass them to other functions.

  • Strive to create functions that are clearly named and have one job with repeatable inputs and outputs.

Last updated