【问题标题】:Compare multiple variables to the same expression将多个变量与同一个表达式进行比较
【发布时间】:2018-05-24 19:25:16
【问题描述】:

我正在尝试将多个变量与一个表达式进行比较,如下所示:

if 1 <= x && x <= 5 &&
    1 <= y && y <= 5 &&
    1 <= z && z <= 5 {
    // Code to run if true
}

我找到了question related to comparing a variable to multiple specific values,这不是我想要的,因为它不是不等式中的比较。

有什么办法可以缩短这个吗?

例如,缩短像 1 &lt;= x &amp;&amp; x &lt;= 5 这样的不等式,或者让我能够以其他方式轻松比较 xyz

【问题讨论】:

    标签: ios swift comparison-operators


    【解决方案1】:

    使用范围!

    if (1...5).contains(x) &&
       (1...5).contains(y) &&
       (1...5).contains(z) {
    
    }
    

    或者,创建一个闭包来检查某物是否在范围内:

    let inRange: (Int) -> Bool = (1...5).contains
    if inRange(x) && inRange(y) && inRange(z) {
    
    }
    

    正如 Hamish 所建议的,Swift 4.2 中的 allSatisfy 方法可以实现为这样的扩展:

    extension Sequence {
        func allSatisfy(_ predicate: (Element) throws -> Bool) rethrows -> Bool {
            return try !contains { try !predicate($0) }
        }
    }
    

    【讨论】:

    • 我什至不知道你能做到这一点!谢谢,这对我有用:)
    • 在 Swift 4.2 中,你甚至可以说 if [x, y, z].allSatisfy((1...5).contains) {} :)
    • @Hamish 我找不到方法allSatisfy。 Xcode 9.3.1 支持 Swift 4.2 对吧?
    • @Sweeper 不,Swift 4.1 附带 Xcode 9.3.1 – Swift 4.2 尚未正式发布,但您可以在 swift.org/download/#snapshots 获取开发快照,您可以将其插入 Xcode .
    • 虽然allSatisfy 的实现非常简单,但它可以很容易地添加到 4.1 的 Sequence 扩展中(然后在 4.2 出现后删除)– func allSatisfy(_ predicate: (Element) throws -&gt; Bool) rethrows -&gt; Bool { return try !contains { try !predicate($0) } }
    【解决方案2】:

    另一种选择:匹配范围元组:

    if case (1...5, 1...5, 1...5) = (x, y, z) {
    
    }
    

    或者使用 switch 语句来匹配一个或多个 范围元组:

    switch (x, y, z) {
    case (1...5, 1...5, 1...5):
        print("all between 1 and 5")
    
    case (..<0, ..<0, ..<0):
        print("all negative")
    
    default:
        break
    }
    

    (比较Can I use the range operator with if statement in Swift?。)

    【讨论】:

      【解决方案3】:

      可能是这样的:

      if [x,y,z].compactMap{ (1...5).contains($0) }.contains(true) {
          //Do stuff
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-07
        • 1970-01-01
        • 2012-01-28
        • 1970-01-01
        相关资源
        最近更新 更多