检查字符串 == 是否"(any of multiple strings)" {} 的最佳方法



我需要一种快速的最佳方法来创建检查字符串与多个字符串的 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 或完全不同的东西吗?

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

最佳方法是制作一个可能的匹配项数组,然后使用 contains 在该数组中查找特定字符串。

let array = ["a", "b", "c"]
if contains(array, segue.identifier) {
    // String found in array
}
在这种情况下

,您应该使用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!
    }
}
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!
}

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

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!
    }
}

最新更新