Swift - Function Function Parameter

Introduction

You can pass parameters to a function.

When you define parameters for a function, you must also define the type of those parameters:

Demo

func addNumbers(firstValue: Int, secondValue: Int) -> Int { 
    return firstValue + secondValue 
} 
let result = addNumbers(firstValue: 1, secondValue: 2) // 3

A Swift function can return a single value.

It can also return multiple values, in the form of a tuple.

You can attach names to the values in the tuple, making it easier to work with the returned value:

func myMethod(firstValue: Int,secondValue: Int) -> (doubled: Int, quadrupled: Int) 
{ 
    return (firstValue * 2, secondValue * 4) 
} 

When you call a function that returns a tuple, you can access its value by index or by name if it has a name:


myMethod(firstValue: 2, secondValue: 4).1 // = 16 // Accessing by number: 
myMethod(firstValue: 2, secondValue: 4).quadrupled // = 16 // Same thing but with names: 

Related Topics