Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef enum in swift

Tags:

enums

swift

I'm rewriting my Objective C application in Swift, and I have a question about enum's. In Objective C you would do;

typedef enum {
stopped,
running
} TimerState;

which returns the errors, Consecutive Declarations on a line must be separated by ‘;’ — Expected declaration — Expected identifier in enum declaration. I read some of the documentation about this and found that you don't put typedef before enum's anymore. So in swift I thought it would be:

enum {
stopped,
running
} TimerState;

But I do not know what to do with the TimerState, does that go inside the curly braces? What do i do. No smart ass comments either, please. Thanks in advance.

like image 454
douglas bumby Avatar asked Jun 10 '14 17:06

douglas bumby


People also ask

What does enum do in Swift?

Enumerations (or enums for short) in Swift define a common type for a group of related values. According to the Swift documentation, enums enable you to work with those values in a type-safe way within your code. Enums come in particularly handy when you have a lot of different options you want to encode.

Can enum conform to Swift protocol?

Yes, enums can conform protocols. You can use Swift's own protocols or custom protocols. By using protocols with Enums you can add more capabilities.

Can enum have functions Swift?

Cases as functions Finally, let's take a look at how enum cases relate to functions, and how Swift 5.3 brings a new feature that lets us combine protocols with enums in brand new ways. A really interesting aspect of enum cases with associated values is that they can actually be used directly as functions.

What is rawValue in Swift?

Enumerations in Swift are much more flexible, and don't have to provide a value for each case of the enumeration. If a value (known as a raw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.


1 Answers

That is not how you declare an enum in Swift. You cannot simply list the values like you could in C. An enum could be accomplished in C with the following technique.

enum TimerState {
    stopped,
    running
};

In swift, you have to use the case keyword.

enum TimerState {
    case stopped
    case running
}

As for the typedef, there is a typealias in swift.

typealias SomeNewEnum = TimerState

Edit: If you want to assign a raw type to your enum, you can do so.

enum TimerState: Int {
        case stopped = 0
        case running // 1
}
like image 188
Brian Tracy Avatar answered Oct 21 '22 11:10

Brian Tracy