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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.