Reducing typo errors with enum

What can be done not to encounter the problem?

Using a set of enum solves the problem. You can create your own enum if the possible values are limited in number in order to reduce typing error.

enum Movement: Int {    case left = 0
case right
case up
case down
}
let move = user.getMovement()switch move {    case .left:
print(“user is moving toward left”)
case .right:
print(“user is moving toward right”)
case .up:
print(“user is moving up”)
case .down:
print(“user is moving down”)
}

Bonus Tip on benefits of using enum

Settings page of iOS
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {if indexPath.row == 0 {
//go to locations page
} else if indexPath.row == 1 {
//go to contacts page
} else if indexPath.row == 2 {
//go to calendar page
} else if indexPath.row == 3 {
//go to reminder page
}
}
enum Row: Int {    case locations = 0,
contacts,
calendar,
reminder
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {if let row = Row(rawValue: indexPath.row) {
switch row {
case .locations:
print(“Go to Location page”)
case .contacts:
print(“Go to Contact page”)
case .calendar:
print(“Go to Calendar page”)
case .reminder:
print(“Go to Reminder page”)
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store