Lazy evaluation
In the previous chapter, we talked about lazily calculated properties on types. These were properties that were not calculated until they were first accessed. We can bring this same concept into functional programming and it actually becomes even more powerful.
First, it is important to realize the order in which these functions are executed. For example, if we only want the first element of our numbers mapped to strings:
var firstString = numbers.map({"\($0)"}).first
This works well except that we actually converted every number to a string to get to just the first one. This is because each step of the chain is completed in its entirety until the next one can be executed. To prevent this, Swift has a built-in function called lazy
.
Essentially, lazy
allows each element to flow through a series of functions one at a time, as needed. You use it to convert a normal list into a lazy list:
firstString = lazy(numbers).map({"\($0)"}).first
Now, instead of calling map
directly on the numbers...