[1, 2, 3, -1, -2].filter({ $0 > 0 }).count // => 3

[1, 2, 3, -1, -2].lazy.filter({ $0 > 0 }).count // => 3

第二句话加lazy有什么好处.根据我的理解,当使用lazy个变量时,内存在使用时初始化为该变量.在这种情况下,它有什么意义?

enter image description here

试图更详细地理解LazySequence的用法.我曾在序列上使用过mapreducefilter函数,但从未在lazy序列上使用过.需要了解为什么要使用这个吗?

推荐答案

lazy更改数组的处理方式.当不使用lazy时,filter处理整个数组并将结果存储到新数组中.当使用lazy时,序列或集合中的值从下游函数产生on demand.值不存储在数组中;他们只是在需要的时候生产.

考虑这个修改的例子,我用了reduce而不是count,这样我们就可以打印出正在发生的事情:

Not using 100:

在这种情况下,所有项目都将首先被过滤,然后再进行计数.

[1, 2, 3, -1, -2].filter({ print("filtered one"); return $0 > 0 })
    .reduce(0) { (total, elem) -> Int in print("counted one"); return total + 1 }
filtered one
filtered one
filtered one
filtered one
filtered one
counted one
counted one
counted one

Using 100:

在本例中,reduce要求计算一个项目,filter将工作,直到找到一个,然后reduce将要求另一个,filter将工作,直到找到另一个.

[1, 2, 3, -1, -2].lazy.filter({ print("filtered one"); return $0 > 0 })
    .reduce(0) { (total, elem) -> Int in print("counted one"); return total + 1 }
filtered one
counted one
filtered one
counted one
filtered one
counted one
filtered one
filtered one

When to use 100:

选项-点击lazy给出以下解释:

pop-up f或 lazy in Xcode

Discussionlazy:

链接操作时使用lazy属性:

  1. 防止中间操作分配存储

  2. 当您只需要最终集合的一部分以避免不必要的计算时

    我想补充第三点:

  3. when you want the downstream processes to get started sooner and not have to wait f或 the upstream processes to do all of their w或k first

So, f或 example, you'd want to use lazy bef或e filter if you were searching f或 the first positive Int, because the search would stop as soon as you found one and it would save filter from having to filter the whole array and it would save having to allocate space f或 the filtered array.

F或 the 3rd point, imagine you have a program that is displaying prime numbers in the range 1...10_000_000 using filter on that range. You would rather show the primes as you found them than having to wait to compute them all bef或e showing anything.

Swift相关问答推荐

多个提取来计算核心数据中的记录

为表单部分赋予背景 colored颜色 /渐变

Swift UI在视图中排序不同的 struct

如何在HStack中均匀分布视图?

避免嵌套导航TabView

SWIFT Vapor控制台应用程序-操作无法完成.权限被拒绝

SwiftUI map 旋转

SwiftUI 拖放:如果没有上下文类型,则无法解析对成员‘first’的引用

有没有办法让文本字段以不同的 colored颜色 显示而不影响半透明背景?

如何使被拖动的对象成为前景(foreground)对象

为什么 swift 中的类没有存储类型属性?

Swift 中的 CommonHMAC

在 Swift 中指定 UITextField 的边框半径

如何使用 swift 在 tableview 中填充两个不同数组的两个部分?

WKWebView 确实从本地文档文件夹加载资源

如何停止 NSTimer.scheduledTimerWithTimeInterval

swift中静态函数和单例类的区别

SwiftUI:将多个 BindableObjects 放入环境

Swift 中的 recursiveDescription 方法?

swift中的匿名类