Carpsen90 Carpsen90 - 4 months ago 7
Swift Question

Laziness in Swift

Why is

lazy
used here?

extension SequenceType {
func mapSome<U>(transform: Generator.Element -> U?) -> [U] {
var result: [U] = []
for case let x? in lazy(self).map(transform) {
result.append(x)
}
return result
}
}


this extension takes a transformation function that returns an optional, and returns an array of only those values that weren’t transformed into nil

Why not just use
self.map(transform)
? is laziness necessary here?

Answer

It avoids the creation of an intermediate array.

self.map(transform)

returns an array containing the results of the transformation of all sequence elements, which would then be traversed to build the resulting array with the non-nil elements.

lazy(self).map(transform)

is a sequence of the transformed elements, which is then iterated over to get the non-nil elements. The transformed elements are computed during the enumeration. (Each call to next() on the lazy sequence produces one element by transforming the next element of the original sequence.)

Both methods work. The lazy method would probably perform better for large sequences, but that can depend on many factors (the size of the array, whether the elements are value or reference types, how costly it is to copy array elements etc). For small arrays the lazy method would probably be slower due to the additional overhead. In a concrete application, profiling with Instruments would help to decide which method to use.