Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access String value in enum without using rawValue

I would like to replace my global string constants with a nested enum for the keys I'm using to access columns in a database.

The structure is as follows:

enum DatabaseKeys {      enum User: String {         case Table = "User"         case Username = "username"         ...     }      ...  } 

Each table in the database is an inner enum, with the name of the table being the enum's title. The first case in each enum will be the name of the table, and the following cases are the columns in its table.

To use this, it's pretty simple:

myUser[DatabaseKeys.User.Username.rawValue] = "Johnny" 

But I will be using these enums a lot. Having to append .rawValue to every instance will be a pain, and it's not as readable as I'd like it to be. How can I access the String value without having to use rawValue? It'd be great if I can do this:

myUser[DatabaseKeys.User.Username] = "Johnny" 

Note that I'm using Swift 2. If there's an even better way to accomplish this I'd love to hear it!

like image 914
Jordan H Avatar asked Aug 30 '15 16:08

Jordan H


People also ask

What is rawValue in enum?

Raw Values If you want to use the three-letter IATA code as the backing value of the enum cases you can do that: Whatever the type you choose, the value you assign to a case is called a rawValue .

Can you give useful examples of enum associated values?

For instance, you might describe a weather enum that lists sunny, windy, and rainy as cases, but has an associated value for cloudy so that you can store the cloud coverage. Or you might describe types of houses, with the number of bedrooms being an associated integer.

What is Rawrepresentable?

A type that can be converted to and from an associated raw value.

What is associated value?

The association value of a stimulus is a measure of its meaningfulness. It is a strong predictor of how easy it is to learn new information about that stimulus, for example to learn to associate it with a second stimulus, or to recall or recognize it in a memory test.


1 Answers

While I didn't find a way to do this using the desired syntax with enums, this is possible using structs.

struct DatabaseKeys {      struct User {         static let identifier = "User"         static let Username = "username"     }  } 

To use:

myUser[DatabaseKeys.User.Username] = "Johnny" 

Apple uses structs like this for storyboard and row type identifiers in the WatchKit templates.

like image 75
Jordan H Avatar answered Nov 22 '22 12:11

Jordan H