[Swift] The story that switch is often used for enum judgment

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.

Judge the enum case with switch

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")
}

Why use enums?

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

[Swift] The story that switch is often used for enum judgment
[Swift] API used for apps that passed the selection
The story that link_to is deep (cause unknown)
The story that .java is also built in Unity 2018
Review the basic knowledge of ruby that is often forgotten
[Ruby] What is `!!` used for?
What is the constructor for?
The story of making a binding for libui, a GUI library for Ruby that is easy to install
The story that a model is not a "correct representation of the real world" / the need for a bounded context
The story of Collectors.groupingBy that I want to keep for posterity
that? WebView (swift) is not working.