Take a look at this code:
enum A { case A1, A2 } enum B : Int { case B1 = 1 case B2 } enum C : String { case C1 case C2 } A.A1.hashValue // 0 A.A2.hashValue // 1 B.B1.hashValue // 0 B.B2.hashValue // 1 C.C1.hashValue // 0 C.C2.hashValue // 1
As you can see, hashValue any enumeration is equal to the case number, regardless of rawValue , and even if it is. This is, of course, because under it, each enumeration is simply a number, and rawValue is just an array that maps these numbers (indices) to the corresponding value. therefore
The transition comparison is just a comparison of two numbers, you can just compare the complexity of hashValue O (1) (untested, but I'm sure)
I don’t know how initialization works with a raw value, most likely it is O (1), although (incorrectly, it is O (n) !, see edit below), because all possible types of rawValue Hashable and therefore it is possible to store them in Hashmap, which will mean O (1) indexing.
Thus, enumeration can be implemented as follows:
enum M : RawRepresentable { case M1 // rawValue = 4, hashValue = 0 case M2 // rawValue = 7, hashValue = 1 typealias RawValue = Int // Int is Hashable -> Store in Dictionary -> O(1) static let rawToEnum : [RawValue : M] = [ 4 : .M1, 7 : .M2 ] // hashValue is index of this array static let hashToRaw : [RawValue] = [ 4, 7 ] var rawValue : RawValue { return M.hashToRaw[hashValue] } init?(rawValue: RawValue) { if let m = M.rawToEnum[rawValue] { self = m } else { self = .M1 // Failed, assign a value to let it compile return nil } } }
EDIT: It seems that enumeration initialization is O (n) (where n is the number of cases) complexity!
I did some performance tests where I created 4 different enumerations with 128, 256, 512, 1024 cases each. Then I made the program select 128 random rawValues of each of these enumerations, create an array from them and repeat this array 20 times (to get a more accurate time). Then the enumeration is initialized by each of these rawValues. Here are the results (build release):
Default rawValue: 20 repetitions 128 cases -> 0.003 sec (33% StDev) 256 cases -> 0.006 sec (14% StDev) 512 cases -> 0.014 sec (15% StDev) 1024 cases -> 0.025 sec (10% StDev)
You can check out the test project I created here (Xcode 7 beta 6)
Another EDIT: I added enumerations to a test project that matches RawRepresentable as I showed above, again using exactly the same setup with 128, 256, 512 and 1024 cases. It turns out (as expected) O (1)! Therefore, apparently, creating your own enumeration is faster! I just don’t understand why Swift developers didn’t do it like this: Performance btw is for a custom implementation of RawRepresentable for more than 200 repetitions (10 times more enumeration initialization than with default rawValues):
Custom rawValue: 200 repetitions 128 cases -> 0.008 sec ( 7% StDev) 256 cases -> 0.008 sec (15% StDev) 512 cases -> 0.010 sec (19% StDev) 1024 cases -> 0.008 sec (26% StDev)