I have a number of Java classes I need to convert to Swift code. One of the classes has an advanced enum:
public enum Student {
STUDENT_ONE("Steve", "Jobs")
STUDENT_TWO("Tim", "Cook")
private String _firstName;
private String _lastName;
}
How can I replicate the same behavior in Swift?
This is what I ended up doing - not sure about this at all:
Moved here from another question marked as a duplicate so the variable names don't match up exactly, however, the concepts all do.
The most obvious way would be:
If you have a single value to associate with each enum case, you can use the raw value syntax, or just use it to simplify the enum case above:
Obviously, if you don't need the name, you can omit the
getName
function. Likewise you can omit thegetDamage
function and just useweapon.rawValue
An even simpler way, and yet more analogous to the actual Java implementation, would be to use a struct instead of an enum, as:
and, be redefining operator ==, you can get equality comparisons:
and, by redefining operator ~= you can get switch to work as expected:
A whole lot of options, mostly it just depends on what you're really trying to do and how much data you need to wrap in the enum.
I was trying to do the same thing with converting Java code to Swift, and ended up doing something like this :
Now, this is really long and messy and I'm not really sure whether this is the right way to do it, but I couldn't find anything else that worked. I would love to know if there is some other better way to do it.
Enums are not necessarily the best choice to represent this type of data. I choose
struct
s and this works well, using the correct accessors:After some thought, I agree with godmoney that aksh1t's solution is better that my solution using Strings.
Anyway, here is a more concise variant of aksh1t's solution, using only one computed property returning a tuple: (tested in Swift 2.0)