理解Swift 2中的延迟函数

时间:2015-12-23 22:09:07

标签: swift

我遇到了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等效的代码?

1 个答案:

答案 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 。这是你想要的吗?