Functions¶Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed. Show
Swift’s unified function syntax is flexible enough to express anything from a simple C-style function with no parameter names to a complex Objective-C-style method with names and argument labels for each parameter. Parameters can provide default values to simplify function calls and can be passed as in-out parameters, which modify a passed variable once the function has completed its execution. Every function in Swift has a type, consisting of the function’s parameter types and return type. You can use this type like any other type in Swift, which makes it easy to pass functions as parameters to other functions, and to return functions from functions. Functions can also be written within other functions to encapsulate useful functionality within a nested function scope. Defining and Calling Functions¶When you define a function, you can optionally define one or more named, typed values that the function takes as input, known as parameters. You can also optionally define a type of value that the function will pass back as output when it’s done, known as its return type. Every function has a function name, which describes the task that the function performs. To use a function, you “call” that function with its name and pass it input values (known as arguments) that match the types of the function’s parameters. A function’s arguments must always be provided in the same order as the function’s parameter list. The function in the example below is called
All of this information is rolled up into the function’s definition, which is prefixed with the The definition describes what the function does, what it expects to receive, and what it returns when it’s done. The definition makes it easy for the function to be called unambiguously from elsewhere in your code:
You call the The body of the You can call the To make the body of this function shorter, you can combine the message creation and the return statement into one line:
Function Parameters and Return Values¶Function parameters and return values are extremely flexible in Swift. You can define anything from a simple utility function with a single unnamed parameter to a complex function with expressive parameter names and different parameter options. Functions Without Parameters¶Functions aren’t required to define input parameters. Here’s a function with no input parameters, which always returns the same
The function definition still needs parentheses after the function’s name, even though it doesn’t take any parameters. The function name is also followed by an empty pair of parentheses when the function is called. Functions With Multiple Parameters¶Functions can have multiple input parameters, which are written within the function’s parentheses, separated by commas. This function takes a person’s name and whether they have already been greeted as input, and returns an appropriate greeting for that person:
You call the Functions Without Return Values¶Functions aren’t required to define a return type. Here’s a version of the
Because it doesn’t need to return a value, the function’s definition doesn’t include the return arrow ( Note Strictly speaking, this version of the The return value of a function can be ignored when it’s called:
The first function, Note Return values can be ignored, but a function that says it will return a value must always do so. A function with a defined return type can’t allow control to fall out of the bottom of the function without returning a value, and attempting to do so will result in a compile-time error. Functions with Multiple Return Values¶You can use a tuple type as the return type for a function to return multiple values as part of one compound return value. The example below defines a function called
The The body of the Because the tuple’s member values are named as part of the function’s return type, they can be accessed with dot syntax to retrieve the minimum and maximum found values:
Note that the tuple’s members don’t need to be named at the point that the tuple is returned from the function, because their names are already specified as part of the function’s return type. Optional Tuple Return Types¶If the tuple type to be returned from a function has the potential to have “no value” for the entire tuple, you can use an optional tuple return type to reflect the fact that the entire tuple can be Note An optional tuple type such as The To handle an empty array safely, write the
You can use optional binding to check whether this version of the
Functions With an Implicit Return¶If the entire body of the function is a single expression, the function implicitly returns that expression. For example, both functions below have the same behavior:
The entire definition of the As you’ll see in Shorthand Getter Declaration, property getters can also use an implicit return. Note The code you write as an implicit return value needs to return some value. For example, you can’t use Function Argument Labels and Parameter Names¶Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.
All parameters must have unique names. Although it’s possible for multiple parameters to have the same argument label, unique argument labels help make your code more readable. Specifying Argument Labels¶You write an argument label before the parameter name, separated by a space:
Here’s a variation of the
The use of argument labels can allow a function to be called in an expressive, sentence-like manner, while still providing a function body that’s readable and clear in intent. Omitting Argument Labels¶If you don’t want an argument label for a parameter, write an underscore (
If a parameter has an argument label, the argument must be labeled when you call the function. Default Parameter Values¶You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.
Place parameters that don’t have default values at the beginning of a function’s parameter list, before the parameters that have default values. Parameters that don’t have default values are usually more important to the function’s meaning—writing them first makes it easier to recognize that the same function is being called, regardless of whether any default parameters are omitted. Variadic Parameters¶A variadic parameter accepts zero or more values of a specified type. You use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. Write variadic parameters by inserting three period characters ( The values passed to
a variadic parameter are made available within the function’s body as an array of the appropriate type. For example, a variadic parameter with a name of The example below calculates the arithmetic mean (also known as the average) for a list of numbers of any length:
A function can have multiple variadic parameters. The first parameter that comes after a variadic parameter must have an argument label. The argument label makes it unambiguous which arguments are passed to the variadic parameter and which arguments are passed to the parameters that come after the variadic parameter. In-Out Parameters¶Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead. You write an in-out parameter by placing the You can only pass a variable as the argument for an in-out parameter. You can’t pass a constant or a literal value as the argument, because constants and literals can’t be modified. You
place an ampersand ( Note In-out parameters can’t have default values, and variadic parameters can’t be marked as Here’s an example of a function called
The You can call the
The example above shows that the original values of Note In-out parameters aren’t the same as returning a value from a function. The Function Types¶Every function has a specific function type, made up of the parameter types and the return type of the function. For example:
This example defines two simple mathematical functions called The type of both of these functions is “A function that has two parameters, both of type Here’s another example, for a function with no parameters or return value:
The type of this function is
Using Function Types¶You use function types just like any other types in Swift. For example, you can define a constant or variable to be of a function type and assign an appropriate function to that variable:
This can be read as: “Define a variable called The You can
now call the assigned function with the name
A different function with the same matching type can be assigned to the same variable, in the same way as for nonfunction types:
As with any other type, you can leave it to Swift to infer the function type when you assign a function to a constant or variable:
Function Types as Parameter Types¶You can use a function type such as Here’s an example to print the results of the math functions from above:
This example defines a function called When
The role of Function Types as Return Types¶You can use a function type as the return type of another function. You do this by writing a complete function type immediately after the return arrow ( The next example
defines two simple functions called
Here’s a function called
You can now use
The example above determines whether a positive or negative step is needed to move a variable called Now that
Nested Functions¶All of the functions you have encountered so far in this chapter have been examples of global functions, which are defined at a global scope. You can also define functions inside the bodies of other functions, known as nested functions. Nested functions are hidden from the outside world by default, but can still be called and used by their enclosing function. An enclosing function can also return one of its nested functions to allow the nested function to be used in another scope. You can rewrite the
What are the functions in programming?A function is simply a “chunk” of code that you can use over and over again, rather than writing it out multiple times. Functions enable programmers to break down or decompose a problem into smaller chunks, each of which performs a particular task.
How is the functions implemented in a programming language?The program comes to a line of code containing a "function call". The program enters the function (starts at the first line in the function code). All instructions inside of the function are executed from top to bottom. The program leaves the function and goes back to where it started from.
What type of programming is defined by the term functional programming?Functional programming is a form of declarative programming. In contrast, most mainstream languages, including object-oriented programming (OOP) languages such as C#, Visual Basic, C++, and Java, were designed to primarily support imperative (procedural) programming.
What is a function in programming example?The function contains instructions used to create the output from its input. It's like a cow that eats grass (the input) which its body turns into milk which a dairy farmer then milks (the output). For example, programming functions might take as input any integer or number.
|