godmoney godmoney - 7 months ago 11
Swift Question

Advanced Java enums in Swift

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?

Answer

I was trying to do the same thing with converting Java code to Swift, and ended up doing something like this :

public enum Student {

    case STUDENT_ONE
    case STUDENT_TWO

    var firstName: String {
        get {
            switch self {
            case .STUDENT_ONE:
                return "Steve"
            case .STUDENT_TWO:
                return "Tim"
            }
        }
    }

    var lastName: String {
        get {
            switch self {
            case .STUDENT_ONE:
                return "Jobs"
            case .STUDENT_TWO:
                return "Cook"
            }
        }
    }
}

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.