我遇到了this article,它解释了lazy
集合和序列的概念,并提供了以下示例代码:
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等效的代码?
答案 0 :(得分:0)
怎么样......
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 。这是你想要的吗?