gpt4 book ai didi

swift - 了解 Swift 2 中的惰性函数

转载 作者:行者123 更新时间:2023-11-30 13:49:41 25 4
gpt4 key购买 nike

我遇到了this article它解释了惰性集合和序列的概念,并具有以下示例代码:

var i = 0
let lf = lazy(1...5).filter { _ in
++i % 2 == 0
}
let a1 = lf.array // a1 is [2, 4]
let a2 = lf.array // a2 is [1, 3, 5]
let a3 = lf.array
// a3 is [2, 4]

在 Swift 2 中,这并不是安静的工作。我认为更新后的版本会更像这样:

var ix = 0
let lf = (1...5).lazy.filter { _ in
++ix % 2 == 0
}

let a1 = lf.array

但是使用 lf.array 会产生错误:

'array' is unavailable: please construct an Array from your lazy sequence: Array(...)

这个错误到底意味着什么?如何实现与此代码等效的 Swift 2?

最佳答案

那……

var ix = 0
let lf = LazyCollection(1...5).filter { _ in
++ix % 2 == 0
}
let a1 = lf
print(a1.count,a1.first!,ix) // yields: 2 2 8

注意:ix 是 8。这是你想要的吗?

关于swift - 了解 Swift 2 中的惰性函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34444487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com