Do you have any concerns about whether to write with an if statement or a switch statement? To be honest, it doesn't matter which one, but when making an enum case judgment I often use switch statements.
Specifically, the code is as follows.
enum Direction {
case top
case right
case bottom
case left
}
var direction:Direction?
//For example, assign right to direction in some conditional expression or processing...
direction = .right
//Judge with switch statement
switch direction {
case .top:
print("direction = top")
case .right:
print("direction = right")
case .bottom:
print("direction = bottom")
case .left:
print("direction = left")
}
By making it possible to select only a fixed pattern, It is used for the purpose of improving maintainability and readability.
It seems that the higher the degree of freedom, the better, but in programming it is rather better. The disadvantages will be greater. Having a high degree of freedom means Each one can be written freely and tends to be complicated code. By daring to put restrictions, you can ensure unity and improve maintainability.
And it is said that the switch statement of the main subject is often used in the judgment of enum, This is just an individual method, and it can be used at all sites. It is not done, so it may be good to use it as a reference.
Recommended Posts