Swift懒惰下标忽略过滤器 [英] Swift lazy subscript ignores filter
问题描述
下标惰性过滤器如何工作?
How does subscripting a lazy filter work?
let ary = [0,1,2,3]
let empty = ary.lazy.filter { $0 > 4 }.map { $0 + 1 }
print(Array(empty)) // []
print(empty[2]) // 3
看起来它只是忽略了过滤器,反正做了地图.这是在某处记录的吗?还有哪些其他惰性集合具有这样的异常行为?
It looks like it just ignores the filter and does the map anyway. Is this documented somewhere? What other lazy collections have exceptional behavior like this?
推荐答案
归结为使用整数对 LazyFilterCollection
下标,在这种情况下,该整数将忽略谓词并将下标操作转发给基数.
It comes down to subscripting a LazyFilterCollection
with an integer which in this case ignores the predicate and forwards the subscript operation to the base.
例如,如果我们要在数组中寻找严格的正整数:
For example, if we're looking for the strictly positive integers in an array :
let array = [-10, 10, 20, 30]
let lazyFilter = array.lazy.filter { $0 > 0 }
print(lazyFilter[3]) // 30
或者,如果我们要在字符串中寻找小写字母:
Or, if we're looking for the lowercase characters in a string :
let str = "Hello"
let lazyFilter = str.lazy.filter { $0 > "Z" }
print(lazyFilter[str.startIndex]) //H
在两种情况下,下标都转发到基本集合.
In both cases, the subscript is forwarded to the base collection.
使用 LazyFilterCollection< Base> .Index
来对 LazyFilterCollection
进行下标的正确方法是,如
The proper way of subscripting a LazyFilterCollection
is using a LazyFilterCollection<Base>.Index
as described in the documentation :
let start = lazyFilter.startIndex
let index = lazyFilter.index(start, offsetBy: 1)
print(lazyFilter[index])
对于数组示例,产生 20
,对于字符串示例,产生 l
.
Which yields 20
for the array example, or l
for the string example.
在您的情况下,尝试访问索引 3
:
In your case, trying to access the index 3
:
let start = empty.startIndex
let index = empty.index(start, offsetBy: 3)
print(empty)
会引起预期的运行时错误:
would raise the expected runtime error :
致命错误:索引超出范围
Fatal error: Index out of range
这篇关于Swift懒惰下标忽略过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!