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.
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.
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.
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.
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.
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
}
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