Bra*_*ley 5 collections range sequence swift swift4
Swift标准库断言:
下降(同时:)
通过跳过元素返回子序列,同时谓词返回 true 并返回剩余元素。
通过使用函数签名:
Run Code Online (Sandbox Code Playgroud)func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
其中predicate
描述为:
一个闭包,它将序列的元素作为其参数,并返回一个布尔值,指示该元素是否匹配。
我的问题是,根据该描述,不应发生以下行为:
let test = (0...3).drop { $0 > 1 }
test.contains(0) // true
test.contains(3) // true
Run Code Online (Sandbox Code Playgroud)
我不明白你为什么不理解这种行为。文档非常清晰并且与输出匹配。
文档说,当谓词为 true 时,该方法将继续跳过(删除)元素。这就像一个 while 循环:
// not real code, for demonstration purposes only
while predicate(sequence.first) {
sequence.dropFirst()
}
Run Code Online (Sandbox Code Playgroud)
并返回剩余的序列。
对于顺序来说0...3
,基本上是[0, 1, 2, 3]
对的?
第一个元素 0 是否满足谓词$0 > 1
?不,所以假想的 while 循环中断,没有任何内容被丢弃,因此返回原始序列。
我认为您将其与“也许”混淆了prefix
?
使用 时prefix
,它将在谓词为 true 时不断向序列添加元素,并在谓词变为 false 时返回序列。
let test = (0...3).prefix { $0 > 1 }
test.contains(0) // false
test.contains(3) // false
Run Code Online (Sandbox Code Playgroud)