2

I am pulling in a list of allowed system codes for my case statement via JSON. They are brought in as a string that looks like the following:

let validCodesFromJson:String = "001, 002, 003, 004, 005, 007, 008, 090, 091, 092, 096"

I then convert this string into an array with the follwing:

let validCodes:NSArray = validCodesFromJson.componentsSeparatedByString(", ")

I need to get this array of codes into the first case of my switch statement.

switch responseArray[selectedResponseTableRow]["code"]! {
        case validCodes:

            successfulPostAnimation()

        case "006":

            showAlertWindow("Alert", message: "Code was 006", buttonText: "OK")

        default:

           showAlertWindow("Alert", message: "Code was not in the list", buttonText: "OK")
        }

The switch statement works if the code is "006" in every other case it is using default. It works fine if I define all of the codes in the first case instead of using the array. But I need to do this programmatically for this project.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Tim B
  • 35
  • 1
  • 6

1 Answers1

7

You can use a guard-clause to increase the complexity of your expression for each particular case. For example:

var validCodes = ["001", "002", "003"]

var code = "002"

switch code {
    case let value where (contains(validCodes, value)):
        "Valid code"
    case "006":
        "Bad code"
    default:
        "Default"
}

If you run this in a playground, you'll see "Valid code".

If you're interested in seeing the grammar/syntax for these kinds of patterns, you can The Swift Programming Language: Statements

Craig Otis
  • 31,257
  • 32
  • 136
  • 234
  • I don't think you need breaks.. ? – Rob Oct 22 '14 at 17:43
  • You're right @Rob, breaks removed. (https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID137) – Craig Otis Jan 13 '16 at 12:36
  • 3
    With Swift 3 I would write the case-condition like this: `case let value where validCodes.contains(value):` – K. Biermann Aug 10 '16 at 10:33