Using Lazy to Delay Computation

iOS Tech Set
Swift Programming
Published in
2 min readFeb 6, 2018

As iOS developers, you may have already heard of lazy keyword used for initialization — the lazy component won’t be created unless someone really wants to interact with it. That’s how lazy works: putting off the work until it needs to do.

Actually, we could do more with it. Not only for property initialization, but also for computation in Swift functional programming.

Let’s see how it works.

Assume that we have a array made up of integers, and we request the result whose value is two times bigger as one element of the original array. Here is the sample code:

let array = [1, 2, 4, 5, 3, 7]
let element = array.map{ $0 * 2 }[3]
print(element)

As you may notice, we only want the 3rd element, while we double the value of all 6 elements in the array, which is redundant and useless.

How to fix it? Using lazy. Swift offers a protocol called LazySequenceProtocol , and there is a lazy variable within its extension to put off computation such as map and filter in functional programming. It is defined as below:

/// Avoid creating multiple layers of `LazySequence` wrapper.
/// Anything conforming to `LazySequenceProtocol` is already lazy.
extension LazySequenceProtocol {

/// Identical to `self`.
public var lazy: Self { get }
}

With lazy , we could fix the original code to make it efficient:

let array = [1, 2, 4, 5, 3, 7]
let element = array.lazy.map{ $0 * 2 }[3]
print(element)

If you copy and paste above code to playground, it would display that in order to get element, the array map function is only executed once.

Have fun with lazy and share your tips on functional programming in the comments below!

--

--