本文介绍了懒惰在斯威夫特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在这里使用lazy?

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
    }
}

此扩展程序采用一个转换函数,该函数返回一个可选值,并仅返回未转换为nil的那些值的数组

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

为什么不只使用self.map(transform)?这里有懒惰吗?

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

推荐答案

它避免了中间数组的创建.

It avoids the creation of an intermediate array.

self.map(transform)

返回一个 array ,其中包含的转换结果 all 序列元素,然后将其遍历以构建包含非nil元素的结果数组.

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

lazy(self).map(transform)

是已转换元素的序列,然后迭代以获得非零元素.转换后的元素是在枚举期间计算的. (每次调用next()在惰性序列上通过转换下一个产生一个元素原始序列的元素.)

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

这两种方法都可以.惰性方法可能会更好地执行对于大序列,但这可能取决于许多因素(大小数组,无论元素是值还是引用类型,复制数组元素等的成本如何).对于小阵列懒惰的方法可能会由于其他原因而变慢高架.在一个具体的应用程序中,使用Instruments进行性能分析会帮助确定使用哪种方法.

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

这篇关于懒惰在斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:25