1

I need a fast optimal way to create if else statement that checks string vs multiple strings

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

Should I use an Array:string, do 9 different if/else or something completely different?

I don't know what would run the code most optimally. Please advise

Chameleon
  • 1,608
  • 3
  • 21
  • 39

4 Answers4

3

The most optimal way is to make an array of the possible matches and then use contains to find a specific string in that array.

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

if contains(array, segue.identifier) {
    // String found in array
}
Ian
  • 12,538
  • 5
  • 43
  • 62
  • ty very much, one last question is it more optimal to state `array` at top of VC1 or in the prepareForSegue that way the array is only created when segue is used? – Chameleon Mar 13 '15 at 05:25
  • I would keep it in the prepareForSegue so it isn't cluttering up the rest of your class and it isn't allocated until it is being used – Ian Mar 13 '15 at 05:27
1

You should use switch in this case:

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!
    }
}
rintaro
  • 51,423
  • 14
  • 131
  • 139
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!
}
Bimawa
  • 3,535
  • 2
  • 25
  • 45
0

Try Following Code .......

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!
    }
}
Nirav Gadhiya
  • 6,342
  • 2
  • 37
  • 76