[Swift / Beginner] Use Enum for maintainable coding

We often use enums to make the code maintainable. Let's take a simple example.

var direction = ""
if right = "right" {
    direction = "right"
} else {
    direction = "left"
}

At first glance, it looks fine. That's right, no problem. However, from the standpoint of maintainability, improvements can be seen.

//File A.swift
enum Direction {
  case right
  case left
}

//File B.swift
var direction:Direction?
if right = "right" {
    direction = .right
} else {
    direction = .left
}

By using enum, we narrow down to ** fixed patterns ** like this You can write the process. This kind of constraint is a very important idea in terms of maintainability in programming. Being free to write means that it is likely to be indefinite and disjointed code. By intentionally restricting and making it inconvenient, you can write code that is in line with regular maintainability.

in conclusion

What did you think It may seem like a hassle, but once you get used to it, it's easy. Writing maintainable code is a beginner, so give it a try.

Recommended Posts

[Swift / Beginner] Use Enum for maintainable coding
[Swift] Use for where rather than nesting for and if
[Swift] Currently, propertyWrapper cannot use Japanese for variable names.
[Swift] Let's use extension
Review Swift enum types