[swift-evolution] Promote "primitive" types to enums in extensions

Carlos Rodríguez Domínguez carlos at everywaretech.es
Thu Mar 24 12:41:14 CDT 2016

It is a common practice in C to assign to integer (int, int16, int64, etc.) typed variables “constant" values declared in enums. In swift, it is in fact possible to do that by using enums' “rawValue” property. When importing structs from C into swift, we even get some fields declared with an integer type, but expecting the assignment of a “constant” declared inside an enum. Of course, this is error prone, it is “old-style” programming and very confusing for newcomers. To solve this issue, my proposal is to be able to create extensions that promote certain fields within a class or struct to enums.

For instance, let’s take these sample C struct and enum:

struct Card {
	int suit;
	int rank;

typedef enum {HEARTS, DIAMONDS, CLUBS, SPADES} CardSuit;

(Note: I understand that above code follows a bad programming practice, yet it is widely common)

It should be imported into swift as follows:

struct Card {

enum CardSuit : Int {
	case Hearts, Diamonds, Clubs, Spades

Now, I propose to be able to create an extension as follows:

extension Card {

From this moment on, the suit field should only receive CardSuit values, thus not requiring the use of raw values for assignments.

These extensions should also be of great interest for people using CoreData, since it is not possible to declare enums in models. Therefore, to declare enums, it is necessary to declare integer values, and then use the “unsafe”, “unexpressive" approach explained before.

Note that the proposal intends to only support promotions from integer values to enum values, but, for example, it could also be extended to string values. 

Finally, it could be appropriate to extend this proposal to redeclare func’s signatures, in order to promote certain parameters to enum values.



More information about the swift-evolution mailing list