Lazy evaluation

A powerful feature of Swift is the ability to make these operations lazily evaluated. This means that, just like a lazy person would do, a value is only calculated when it is absolutely necessary and at the latest point possible.

First, it is important to realize the order in which these methods are executed. For example, what if we only want the first element of our numbers to be mapped to strings:

var firstString = numbers.map({String($0)}).first

This works well, except that we actually converted every number to a string to get to just the first one. That is because each step of the chain is completed in its entirety before the next one can be executed. To prevent this, Swift has a built-in method called lazy.

Lazy creates a new version of a container that only pulls specific values from it when it is specifically requested. This means that lazy essentially allows each element to flow through a series of functions one at a time, as it is needed. You can think about it like a lazy version of a worker. If you ask someone lazy to look up the capital of Cameroon, they aren't going to compile a list of the capitals of all countries before they get the answer. They are only going to do the work necessary to get that specific answer. That work may involve multiple steps, but they would only have to do those steps for the specific countries you ask for.

Now, let's look at what lazy looks like in code. You use it to convert a normal list into a lazy list:

firstString = numbers.lazy.map({String($0)}).first

Now, instead of calling map directly on numbers, we called it on the lazy version of numbers. This makes it so that every time a value is requested from the result, it only processes a single element out of the input array. In our preceding example, the map method will only have been performed once.

This even applies to looping through a result:

let lazyStrings = numbers.lazy.map({String($0)})
for string in lazyStrings {
    print(string)
}

Each number is converted to a string only upon the next iteration of the for-in loop. If we were to break out of that loop early, the rest of the values would not be calculated. This is a great way to save processing time, especially on large lists.

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

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