【问题标题】:How to specify a range to avoid in Swift如何在 Swift 中指定要避免的范围
【发布时间】:2018-12-09 23:50:40
【问题描述】:

我正在努力做到这一点,所以当我提供一个不在 30 年代的值时,它会打印出一条特定的消息。这是我的代码:

let age = 25

if case 18...25 = age {
  print("Cool demographic")
}
else if case !(30...39) = age {
  print("not in there thirties")
}

【问题讨论】:

    标签: swift


    【解决方案1】:

    您可以使用模式匹配运算符~=

    static func ~= (pattern: Range<Bound>, value: Bound) -> Bool
    

    您可以使用此模式匹配运算符 (~=) 来测试一个 值包含在一个范围内。以下示例使用 ~= 运算符来测试一个整数是否包含在一个范围内 数字。

    let age = 29
    
    if 18...25 ~= age {
        print("Cool demographic")
    } else if !(30...39 ~= age) {
        print("not in there thirties") // "not in there thirties\n"
    }
    

    【讨论】:

      【解决方案2】:

      我喜欢contains,而不是不必要的晦涩if case。在某些情况下需要if case,但这不是其中之一。很高兴说出你的意思。所以:

      let age = 25
      
      if (18...25).contains(age) {
          print("Cool demographic")
      }
      else if !(30...39).contains(age) {
          print("not in their thirties")
      }
      

      【讨论】:

        【解决方案3】:

        如果age是整数,可以直接比较:

        if age < 30 || age > 39 {
            print("not in thirties")
        }
        

        【讨论】:

        • 谢谢你的工作!为什么我没有想到:P
        【解决方案4】:

        你也可以使用switch,在我看来它比if-else更有表现力一点:

        let age = 25
        
        switch age {
        case 18...25:
            print("Cool demographic")
        case _ where !(30...39 ~= age):
            print("not in there thirties")
        default:
            break
        }
        

        您可以找到来自this link 的 Imanou Petit 的 switch 的好例子:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-04-07
          • 2021-11-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-25
          相关资源
          最近更新 更多