'Is it possible to combine switch case default and some of the case when they do the same thing
I have a question about switch case in Swift. I have a struct
struct State {
static let initialized = "init"
static let ready = "ready"
static let recording = "recording"
static let finished = "finished"
static let error = "error"
}
and I want to return UIImage depending on the current State.
func getHeaderIconImage(from status: String) -> UIImage {
var result = UIImage()
switch status {
case State.ready, State.finished:
result = Images.ready
case State.recording:
result = Images.ongoing
case State.initialized, State.error:
result = Images.notReady
default:
result = Images.notReady
}
return result
}
Basically, the default part should not be triggered, but without the default part Swift will yelling at me with Switch must be exhaustive error, so I need to include the default case. Since I do the exact same thing for the .initialized, .error case, and the default case, probably it's better to combine those three parts and I should only write it down the default case. However, I though if I can also write the .initialized case and the .error case, it's more clear since I can list all the cases in the switch case.
So, I was wonderign if there is a way to refactor the switch state to combine the default case with some other cases if they do exactly the same thing? Or I cannot and either leave the .init & .error case and default, or get rid of the .init & .error part?
Solution 1:[1]
You are switching over a String value. The compiler doesn't know you are only using the static properties of your State struct, and technically you are not limited to that. So, in this case the compiler knows that other String values are possible and you need to add a default case. When you use an enum:
enum State: String {
case initialized = "init"
case ready = "ready"
case recording = "recording"
case finished = "finished"
case error = "error"
}
The compiler knows all possible case and won't force you to use a default case.
Using the enum, your function should look like this:
getHeaderIconImage(from status: State) -> UIImage
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcel |
