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?
It is better to create an enum with cases in the following scenarios:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With