Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum of tuples in Swift

Tags:

swift

Is this possible to create a enum of Tuples in Swift?

I'd like to build something like:

enum ErrorCode: (Int, String) {     case Generic_Error = (0, "Unknown")     case DB_Error = (909, "Database") } 

But it doesn't compile... Is there a way to obtain a similar result?

like image 801
MatterGoal Avatar asked Oct 15 '14 16:10

MatterGoal


2 Answers

Swift enumerations cannot have Tuples as a raw value type.

Alternative approaches include storing the code and deriving a description from that:

enum ErrorCode: Int, CustomStringConvertible {     case Generic = 0     case DB = 909      var description: String {         switch self {         case .Generic:             return "Unknown"         case .DB:             return "Database"         }     } } 

...or storing associated values for code and description in the enumeration cases themselves:

enum Error {     case Generic(Int, String)     case DB(Int, String) } 

If you're just looking for constant values, @matt's suggestion of organizing them within a struct would work, too.

like image 149
mattt Avatar answered Oct 13 '22 21:10

mattt


It depends what you mean by "similar". What I do is use a Struct with static constant properties:

struct Trouble {     static let Generic_Error = (0, "Unknown")     static let DB_Error = (909, "Database") } 

Now things like Trouble.Generic_Error are usable throughout your code.

like image 43
matt Avatar answered Oct 13 '22 21:10

matt