Reputation: 5195
Maybe I misunderstand enums in swift, but in obj-c I was using enums like this (and using a lot):
class SomeObject;
typedef NS_ENUM(NSUInteger, SomeType) {
Type1 = 0,
Type2, // = 1
Type3, // = 2
TypeInvalid // = 3
};
- (SomeType)getTypeOf(NSArray *a, SomeObject *o) {
//for (int i = 0; i < a.count; ++i)
// if ([a[i] isEqual:o])
// return i;
NUInteger result = [a indexOfObject:o];
return result == NSNotFound ? TypeInvalid : result;
}
// Also I could use this:
a[Type3] = someObject;
How to do the same in Swift? Am I forced to use constants (let Type1 = 0
), like in Java (public static final int Type1 = 0;
)?
Upvotes: 1
Views: 7067
Reputation: 19239
In addition to Ed Gamble response, you can also set enum values manually:
enum SomeType : Int {
case Type1 = 1
case Type2 = 2
case Type3 = 3
case TypeInvalid = -1
}
Using Swift enums you are not limited to Int
values:
enum SomeType : String {
case Type1 = "Type 1"
case Type2 = "Type 2"
case Type3 = "Type 3"
case TypeInvalid = "Invalid type"
}
To get the inner value, you call rawValue
:
let foo = SomeType.Type2
foo.rawValue // returns "Type 2"
And you can construct enums from values using init(rawValue:)
method:
let rawValue = "Type 2"
let foo = SomeType(rawValue: rawValue)
Note that this init
returns an optional, because it may not found a valid enum associated to that value. Having a default value makes error handling much easier:
let foo = SomeType(rawValue: rawValue) ?? SomeType.TypeInvalid
Upvotes: 3
Reputation: 70135
Simply:
enum SomeType : Int {
case Type1, Type2, Type3, TypeInvalid
}
The Apple documentation states:
By default, Swift assigns the raw values starting at zero and incrementing by one each time
So you get Type1 with a rawValue
of 0
. For example:
1> enum Suit : Int { case Heart, Spade, Diamond, Club }
2> Suit.Heart.rawValue
$R0: Int = 0
3> Suit.Club.rawValue
$R1: Int = 3
Note: In your example code, you'll need to replace return i
with return SomeType(rawValue: i)!
(although I don't quite understand the logic as apparently i
is limited by a.count
which might not correspond to a SomeType
value)
Upvotes: 6