I am working on a mini programme that input some variables and return results base on conditions.
My conditions code works fine, but it looks complicated and hard to read
I am trying to use switch statement to simplify it but faced some issues.
These are the variables:
@State var adultRequiredMinAge:Int = 0
@State var adultRequireDose:Int = 0
@State var kidRequiredMinAge:Int = 0
@State var kidRequireDose:Int = 0
@State var actualAge:Int?
@State var Dose:Int = 0
@State var adultLastDoseNotExpired:Bool = false
@State var kidLastDoseNotExpired:Bool = false
@State var hasMEC:Bool = false
@State var mecNotExpired:Bool = false
@State var vaccinePass = ""
@State var TestSwitchResult = ""
and these are the conditions, it works fine:
Text(vaccinePass)
Button {
//Vaccine record have age
if let actualAge = actualAge {
//has MEC
if hasMEC == true && mecNotExpired == true {
vaccinePass = "MEC"
//No MEC
} else if hasMEC == false || mecNotExpired == false {
//Adult
if actualAge >= adultRequiredMinAge {
if Dose >= 1 && Dose >= adultRequireDose && adultLastDoseNotExpired == true {
vaccinePass = "Fully Vaccinated - Adult"
} else if (Dose >= 1 && Dose <= adultRequireDose) || (Dose >= 1 && adultLastDoseNotExpired == false) {
vaccinePass = "Partly Vaccinated - Adult"
} else {
vaccinePass = "Not Vaccinated - Adult"
}
}
//Kid
else if actualAge <= adultRequiredMinAge && actualAge >= kidRequiredMinAge {
if Dose >= 1 && Dose >= kidRequireDose && kidLastDoseNotExpired == true {
vaccinePass = "Fully Vaccinated - Kid"
} else if (Dose >= 1 && Dose <= kidRequireDose) || (Dose >= 1 && kidLastDoseNotExpired == false) {
vaccinePass = "Partly Vaccinated - Kid"
} else {
vaccinePass = "Not Vaccinated - Kid"
}
//Baby
} else if actualAge < kidRequiredMinAge {
vaccinePass = "MEC - Baby"
}
}
//Vaccine record don't have age
} else if actualAge == nil{
if Dose >= adultRequireDose && adultLastDoseNotExpired {
vaccinePass = "Fully Vaccinated - No Age"
} else if Dose >= 1{
vaccinePass = "Partly Vaccinated - No Age"
} else {
vaccinePass = "Not Vaccinated - No Age"
}
}
} label: {
Text("Submit")
}
And I try to make it to a switch statement, may be I don’t really get how to use it, i have just typed a few lines and already faced bugs:
"Expression pattern of type ‘Bool’ cannot match values of type ‘String’"
Text(TestSwitchResult)
Button {
switch TestSwitchResult {
case Dose >= adultRequireDose && adultLastDoseNotExpired == true : "Fully Vaccinated - No Age"
case Dose >= 1 : "Partly Vaccinated - No Age"
default: "Not Vaccinated - No Age"
}
} label: {
Text("Switch Test")
}
Can I use switch statement in my case? if no, any alternative way to simplify the condition code?
thx