Swift 4 Programming Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

Let's look at how functions are defined in Swift:

func nameOfFunction(parameterLabel1 parameter1: ParameterType1, parameterLabel2 parameter2: ParameterType2,...) -> OutputType { 

// Function's implementaion
// If the function has an output type,
// the function must return a valid value
return output
}

Let's look at this in more detail to see how a function is defined:

  • func : This indicates that you are declaring a function.
  • nameOfFunction : This will be the name of your function, and by convention is written in camel case (this means that each word, apart from the first, is capitalized and all spaces are removed). This should describe what the function does, and should provide some context to the value returned by the function, if one is returned. This will be how you will invoke the method from elsewhere in your code, so bear that in mind when naming it.
  • parameterLabel1 parameter1: ParameterType1 : This is the first input, or parameter, into the function. You can specify as many parameters as you like, separated by commas. Each parameter has a parameter name (parameter1) and type (ParameterType1); the parameter name is how the value of the parameter will be made available to your function's implementation. You can optionally provide a parameter label in front of the parameter name (parameterLabel1 ), which will be used to label the parameter when your function is used (at the call site).
  • -> OutputType : This indicates that the function returns a value and indicates the type of that value. If no value will be returned, this can be omitted. In the following code illustration, the curly brackets indicate the start and end of the function's implementation; anything within them will be executed when the function is called:
{  
// Function's implementaion
}
  • return output : If the function returns a value, you type return and then the value to return. This ends the execution of the function; any code written after the return statement is not executed.

Now, let's put this into action.