Swift Introduction | Functions | Defining and Using Functions

The examples so far have executed statements sequentially, but real programs are more complex.

Group reusable processes so that they can be called whenever needed. A function provides this capability.

In Swift, define and call a function as follows.

func functionName(arguments) -> ReturnType {
    ...... process to perform ......
    return value
}

Specify arguments inside parentheses after the function name. Write each argument as a name and type pair, such as variableName:Type. Separate multiple arguments with commas.

After ->, specify the return type. If the function does not return a value, specify Void or omit the return type. Swift then treats it as Void.

Use return to return a value. A function returning Void does not need return.

The following is a simple example.

func calc(num:Int) -> Int {
    var total:Int = 0
    for i in 1...num {
        total += i
    }
    return total
}
 
calc(100)

This code declares and calls calc, a function that receives an integer and returns the sum from 1 through that value. The declaration calc(num:Int) shows that the function receives one Int argument. The -> Int declaration shows that it returns an Int.