Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a technical reason to use Swift's caseless enum instead of real cases?

Tags:

enums

swift

Being new to Swift this is what I found:

enum HttpMethod {
  static let post = "POST"
  static let get = "GET"
}

// can assign to string property.
request.httpMethod = HttpMethod.post // --> "POST"

The reason to use a caseless enum and not a struct makes sense to me after reading this but is not the thing I'm interested here.

Having a strong C# background this is how I would implement it:

enum HttpMethod: String {
  case post = "POST"
  case get = "GET"
}

// I'd even consider this alternatively:
enum HttpMethod: String {
  case post
  case get
}

// Must retrieve string value
request.httpMethod = HttpMethod.post.rawValue // --> "POST" or "post"

The second version requires the usage of rawValue but it treats the enum as a real enum. Coming from C# I'm used to using .ToString() on enum values.

Is this all just coming down to personal preference and Swift's conventions to use a caseless enum instead of actual cases + rawValue, or is there another (technical) reason to prefer the first over the second version?

like image 831
Krumelur Avatar asked Mar 06 '23 14:03

Krumelur


1 Answers

Enum with cases

It is better to create an enum with cases in the following scenarios:

  • It is mutually exclusive
  • Finite set of values that you know at compile time
  • You are the one defining it (If an enum is defined in a framework you wouldn't be able to extend it to add more cases)

Advantage of an enum are:

  • Since the values are a finite set, you can write exhaustive switch statements
  • cleaner code

Static values:

When a struct / class is defined in a framework and you want to extend it to add more values.

Example of where this approach is used is Notification.Name in Foundation

Note:

  • enums in swift are quite powerful
  • enums can have associated values
  • enums can have other functions. (if you are defining states like start, inProgress, finished, you could define a function called next, which could return the next state. start.next()
  • if you are in a scenario where values are not mutually exclusive, like it could a combination of values then use OptionSet instead

Conclusion

  • It all depends on your intent

  • If you know the values before hand and they will not change, then create an enum

  • If that is not possible then create static values.

  • If you are creating static values, you are compromising so you don't have to use it in an enum, you could define it as a struct so that the intent is clearer.

  • This is as of now, there is a swift proposal for extendable enums

like image 117
user1046037 Avatar answered Apr 27 '23 22:04

user1046037