Mario Boikov
1 min readMar 21, 2016

Switch-less extraction of enum associated values in Swift

If you’ve used enums with associated values you’ve probably used a switch-statement to extract the value.

enum LocationEvent {
case LocationUpdate(CLLocation)
case Authorization(CLAuthorizationStatus)
}
func locationEventArrived(event: LocationEvent) {
switch event {
case .LocationUpdate(let location):
debugPrint("Location updated: \(location)")
default:
debugPrint("Not a location update")
}
}

There’s nothing wrong with the locationEventArrived implementation but it probably requires the readers attention to figure out which enum values the function body handles. After reading the function you probably realize that the function only handles LocationUpdate events. To make the intention more clear we can replace the switch-statement with a guard-statement.

func locationEventArrived(event: LocationEvent) {
guard case .LocationUpdate(let location) = event else {
debugPrint("Not a location update")
return
}
debugPrint("Location updated: \(location)")
}

If you prefer using if-statements over guard-statements, the code above can be rewritten as.

func locationEventArrived(event: LocationEvent) {
if case .LocationUpdate(let location) = event {
debugPrint(“Update map with location: \(location)”)
} else {
debugPrint(“Not a location update, returning…”)
}
}

Personally, I prefer using guard over if in situations like the above. I think the intention of guard is more clear, it tells the reader what the function’s prerequisites are.

Thanks for reading.

Mario Boikov

Owner Red Shark AB. Software developer with passion for UI/UX. Wannabe guitarist.