Functional programming is a programming paradigm where you model everything as a result of a function that avoids changing state and mutating data. We will discuss concepts such as state and data mutability and their importance in subsequent sections, but for reference, consider state as one of the different permutations and combinations that your program can have at any given time during its execution, whereas data mutability is the concept where a given dataset might change over a given course of time during program execution.
The same example that was given using imperative programming can be used in the following way using the functional approach:
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let numbersLessThanFive = numbers.filter { $0 < 5 }
We feed the filter function with a closure containing a certain criterion that is then applied to each element in the numbers array, and the resulting array contains elements that satisfy our criteria.
Notice the declaration of the two arrays in both the examples.
In the first example, theĀ numbersLessThanFive array was declared as a var, whereas in the second example, the same array was declared as a let. Does it ring some bells? Which approach is better, which array is safer to work with? What if more than one thread is trying to work with the same array and its elements? Isn't a constant array more reliable? Let's answer all those questions in the data immutability section later in this chapter.