【问题标题】:How do I check a condition for every element in an array?如何检查数组中每个元素的条件?
【发布时间】:2016-06-20 22:38:16
【问题描述】:

我有一段代码,只有当数组中的每个元素的某些条件都为真时,我才想运行该代码。目前,我必须知道数组的长度才能使任何代码起作用,但我的最终目标是让它适用于任何长度的数组。

我当前的代码:

if (rand[0] == someInt && rand[1] == someInt && . . . && rand[n] == someInt) {

    *do some things*

}

我希望它在不知道 rand 的长度的情况下工作。

【问题讨论】:

标签: arrays swift loops if-statement control-flow


【解决方案1】:

在 Swift 3 中,使用 first(where:),这很简单:

extension Sequence {
    func allPass(predicate: (Iterator.Element) -> Bool) -> Bool {
        return first(where: { !predicate($0) }) == nil
    }
}

在 Swift 2.2 中,类似:

extension SequenceType {
    func allPass(predicate: (Generator.Element) -> Bool) -> Bool {
        for element in self {
            if !predicate(element) { return false }
        }
        return true
    }
}

在任何一种情况下,当它们找到第一个失败的元素时,它们会立即返回 false。

【讨论】:

    【解决方案2】:

    一个常见的实现是使用到contains的基本转换和两个否定:

    // all equal to someInt <=> there is none that is not equal to someInt
    if !(rand.contains { $0 != someInt }) {
      ...
    }
    

    extension Sequence {
        public func allSatisfy(where predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Bool {
            return try !self.contains { element throws -> Bool in
                return try !predicate(element)
            }
        }
    }
    
    if (rand.allSatisfy { $0 == someInt }) {
      ...
    }
    

    不过,这个方法最终在 Swift 4.2(Xcode 10+,见 SE-207)中被添加到 Swift 标准库中,因此不需要扩展。

    【讨论】:

      【解决方案3】:

      除了reduce,您可能还想了解filter,如果您关心“其他”情况或衡量您离成功有多近,这可能会有所帮助。例如:

      let matches = rand.filter { $0 == someInt }
      
      if rand.count == matches.count {
          print("there were \(matches.count) matches")
          // do some things
      } else {
          print("there were only \(matches.count) of \(rand.count) total possible matches")
      }
      

      【讨论】:

      • arrayName.filter { $0.propertyName == true }
      【解决方案4】:

      试试这个:

      if rand.reduce(true, combine: {$0 && $1 == someInt})
      {
          print("do some thing")
      }
      

      reduce 函数允许您提供一个初始值和一个闭包,该闭包将该类型的值和数组元素映射到与初始值相同类型的值,然后将该函数应用于大批。所以这只是将数组的每个元素与您想要的值进行比较的结果。从概念上讲,这与您最初编写的内容相同。

      如果您还没有看到 $0 和 $1,他们可能会感到困惑;它们只是你提供给 reduce 的匿名闭包的参数,在这种情况下,$0 是一个布尔值,$1 是你数组的一个元素。

      【讨论】:

        猜你喜欢
        • 2014-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-17
        • 1970-01-01
        • 2019-07-03
        • 2020-09-15
        相关资源
        最近更新 更多