Function Parameter Names in Swift

The general Syntax of the function is as follows.

However, these parameter names are only used within the body of the function itself, and cannot be used when calling the function. These kinds of parameter names are known as local parameter names, because they are only available for use within the function’s body.

External Parameter Names

If you want users of your function to provide parameter names when they call your function, define an external parameter name for each parameter, in addition to the local parameter name. You write an external parameter name before the local parameter name it supports, separated by a space. the following is the syntax.

If you provide an external parameter name for a parameter, that external name must always be used when you call the function.

The following is an example which demonstrates the use of local  parameter value and function definition.

The following is the function call.

The following is an example which demonstrates the use of external parameter value and function definition.

The following is the function call.

  •  Consider using external parameter names whenever the purpose of a function’s arguments would be unclear to someone reading your code for the first time.
  • You do not need to specify external parameter names if the purpose of each parameter is clear when the function is called.

 

Shorthand External Parameter Names

Write the name once, and prefix the name with a hash symbol (#). This tells Swift to use that name as both the local parameter name and the external parameter name.

This example defines a function called containsCharacter, which defines external parameter names for both of its parameters by placing a hash symbol before their local parameter names:

the following is the function call.

Default Parameter Values:

If no value is provided when the function is called, the default value of a single space (" ") is used instead:

following is the example.

In the function call joiner takes no value as it is not mentioned in the function call. Thus its default value ” ” (space) is used.

External Names for Parameters with Default Values:

Here’s a version of the join function from earlier, which provides a default value for its joiner parameter:

In this case, Swift automatically provides an external parameter name for the joiner parameter. The external name must therefore be provided when calling the function, making the parameter’s purpose clear and unambiguous:

If a string value for joiner is provided when the join function is called, that string value is used to join the two strings together.

  • You can opt out of this behaviour by writing an underscore (_) instead of an explicit external name when you define the parameter. However, external names for parameters with default values are preferred.

Next we will learn about constants and variable parameter in functions.