Home > other >  Multiple switch statement with conditional inside
Multiple switch statement with conditional inside

Time:01-03

Is there a cleaner way of writing the conditional for case "1", "4", "7"? For this case I want to write to the string "b" only if the string value is not "4".

var b = ""
var c = ""

let s = "4"

switch s {
case "0", "6", "8":
    c  = "|_|"
case "1", "4", "7":
    if s != "4" { b  = "  |" }
    c  = "  |"
case "2":
    c  = "|_ "
case "3", "5", "9":
    c  = " _|"
default:
    c  = ""
}

CodePudding user response:

I think the whole idea of switch statement is that you don’t use ifs inside. You should probably just create a separate case for “4”. The amount of space saved by putting this conditional isn’t worth obscuring the code IMO.

CodePudding user response:

This is a place you could use the fallthrough statement:

switch s {
case "0", "6", "8":
    c  = "|_|"
case "1", "7":
    b  = "  |"
    fallthrough
case "4":
    c  = "  |"
case "2":
    c  = "|_ "
case "3", "5", "9":
    c  = " _|"
default:
    break
}

Since you want "1" and "7" to execute both statements, give them their own case and then follow it with fallthough which allows it to fall though to the next case. Then "1", "4", and "7" will all execute the code in the case "4": case.

  • Related