Returning values from functions

Swift functions can return a value, tuple, closure, or another function. The ability of a function to return a closure or function is an essential concept for FP as it empowers us to compose with functions. We will get into the use of it when we talk about first-class and higher-order functions.

Syntax-wise, we can specify that a function returns by providing ReturnType after ->. For instance, the following example returns String:

func functionName() -> String { } 

Any function that has ReturnType in its definition should have a return keyword with the matching type in its body.

return types can be optionals in Swift, so the function becomes as follows for our previous example:

func functionName() -> String? { } 

Tuples can be used to provide multiple return values. For instance, the following function returns a tuple of the (Int, String) type:

func functionName() -> (code: Int, status: String) { } 

Tuple return types can be optional too, so the syntax becomes as follows:

func functionName() -> (code: Int, status: String)? { } 

This syntax makes the entire tuple optional. If we want to make only status optional, we can define the function as follows:

func functionName() -> (code: Int, status: String?) { } 

In Swift, functions can return functions. The following example presents a function with the return type of a function that takes two Int values and returns an Int value:

func funcName() -> (Int, Int)-> Int {} 

If we do not expect a function to return any value, tuple, or function, we simply do not provide ReturnType:

func functionName() { } 

We could also explicitly declare it with the Void keyword as follows:

func functionName() -> Void { } 

In FP, it is important to have return types in functions. In other words, it is good practice to avoid functions that have Void as a return type. A function with the Void return type typically is a function that changes another entity in the code; otherwise, why would we need to have a function?

OK, we might have wanted to log an expression to the console, save a file or write data to a database or a file to a filesystem. In these cases, it is also preferable to have a return or feedback related to the success of the operation. As we try to avoid mutability and stateful programming in FP, we can assume that our functions will have returns in different forms.

This requirement is in line with the mathematical underlying bases of FP. In mathematics, a simple function is defined as follows:

y = f(x) or f(x) -> y 

Here, f is a function that takes x and returns y. Therefore, a function receives at least one parameter and returns at least a value. In FP, following the same paradigm makes reasoning easier, function composition possible, and code more readable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset