Gro*_*uff 3 arrays loops if-statement control-flow swift
我有一段代码,仅当数组中的每个元素都满足某些条件时才运行它。目前,我必须知道任何代码才能工作的数组长度,但我的最终目标是让它适用于任何长度的数组。
我当前的代码:
if (rand[0] == someInt && rand[1] == someInt && . . . && rand[n] == someInt) {
*do some things*
}
Run Code Online (Sandbox Code Playgroud)
我希望这个在不知道 的长度的情况下工作rand
。
在 Swift 3 中,使用first(where:)
,这非常简单:
extension Sequence {
func allPass(predicate: (Iterator.Element) -> Bool) -> Bool {
return first(where: { !predicate($0) }) == nil
}
}
Run Code Online (Sandbox Code Playgroud)
在 Swift 2.2 中,类似:
extension SequenceType {
func allPass(predicate: (Generator.Element) -> Bool) -> Bool {
for element in self {
if !predicate(element) { return false }
}
return true
}
}
Run Code Online (Sandbox Code Playgroud)
无论哪种情况,当它们找到第一个失败元素时,它们都会立即返回 false。