检查string ==“(多个字符串中的任何一个)”{}的最佳方法

时间:2015-03-13 05:00:51

标签: ios swift

我需要一种快速优化的方法来创建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!
    }

我应该使用数组:字符串,执行9种不同的if / else或完全不同的内容吗?

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

4 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

在这种情况下你应该使用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!
    }
}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

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