Lesson 4

Functions

A function is a collection of instructions that perform a specific task; the task is usually something that needs to be performed multiple times over the life of the application. A function has a name, which is used to call it from other parts of your application. A function may return a value (perhaps the result of a computation) and could also have one or more input parameters.

Declaring Functions

Every function has a name; the name given to a function typically describes what it does. Functions are declared in Swift using the func keyword. The following example declares a simple function called greetUser that prints a line to the console using print:

func greetUser ()
{
    print("Hello there!")
}

To call this function from other parts of your code, you will simply need to mention the name of the function:

greetUser()

Parameters and Return Values

As mentioned earlier, functions can return values and accept input parameters; both of these are optional but at the very least, most functions accept one or more input parameters. The following example declares the function cubeNumber, which accepts a single integer as input and returns its cube as output.

func cubeNumber (inputValue:Int) -> Int
{
    return inputValue * inputValue * inputValue
}

Any input parameters are declared in the parentheses, and the return type of the function is specified using the return arrow (->). Functions aren't restricted to a single input parameter. The following example declares ...

Get Swift iOS 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.