Carpsen90 Carpsen90 - 1 year ago 47
Swift Question

Laziness in Swift

Why is

used here?

extension SequenceType {
func mapSome<U>(transform: Generator.Element -> U?) -> [U] {
var result: [U] = []
for case let x? in lazy(self).map(transform) {
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
? is laziness necessary here?

Answer Source

It avoids the creation of an intermediate array.

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.


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.