【问题标题】:Most optimal way to check if string == "(any of multiple strings)" {}检查 string == "(any of multiple strings)" {} 的最佳方法
【发布时间】:2015-03-13 05:00:51
【问题描述】:

我需要一种快速优化的方法来创建检查字符串与多个字符串的 if else 语句

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "ANY OF MULTIPLE STRINGS 'x1'-'x9'"{
        let JVC = segue.destinationViewController as VC3
        JVC.betSource = segue.identifier!     
    } else {
        let KVC = segue.destinationViewController as VC2
        KVC.source = segue.identifier!
    }

我应该使用 Array:string,做 9 种不同的 if/else 还是完全不同的东西?

我不知道什么会以最佳方式运行代码。请指教

【问题讨论】:

标签: ios swift


【解决方案1】:

最优化的方法是创建一个可能匹配的数组,然后使用contains 在该数组中查找特定字符串。

let array = ["a", "b", "c"]

if contains(array, segue.identifier) {
    // String found in array
}

【讨论】:

  • 非常好,最后一个问题是在 VC1 顶部或 prepareForSegue 中声明 array 是否更理想,这样只有在使用 segue 时才创建数组?
  • 我会将它保存在 prepareForSegue 中,这样它就不会把你的其他班级弄得一团糟,并且在使用之前不会分配
【解决方案2】:

在这种情况下你应该使用switch

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    switch segue.identifier! {
    case "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9":
        let JVC = segue.destinationViewController as VC3
        JVC.betSource = segue.identifier!
    default:
        let KVC = segue.destinationViewController as VC2
        KVC.source = segue.identifier!
    }
}

【讨论】:

    【解决方案3】:
    var str = "x1 x2 x3 x4 x5 x6 x7 x8 x9"
    if(str.rangeOfString(segue.identifier)) 
    let JVC = segue.destinationViewController as VC3
        JVC.betSource = segue.identifier!     
    } else {
        let KVC = segue.destinationViewController as VC2
        KVC.source = segue.identifier!
    }
    

    【讨论】:

      【解决方案4】:

      尝试以下代码.......

      override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 
      {
          var string = "ANY OF MULTIPLE STRINGS 'x1'-'x9'"
      
          if string.rangeOfString(segue.identifier) != nil 
          {
              let JVC = segue.destinationViewController as VC3
              JVC.betSource = segue.identifier!     
          }
          else
          {
              let KVC = segue.destinationViewController as VC2
              KVC.source = segue.identifier!
          }
      }
      

      【讨论】:

      • 我猜这会起作用,但我计划为其他 segue 展开添加更多 else 语句。 ty
      猜你喜欢
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 2014-10-08
      • 2022-11-25
      • 2010-10-12
      • 2011-04-30
      相关资源
      最近更新 更多