Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to add properties

Tags:

swift

In Swift 2.1, I am trying to use reflection in order to add cases generated from a text file to an enum at compile time.

Here is the enum wrapper:

enum Kind : Int { 

}

Using C/++ I could just use this macro:

#define X(value, left, right) \
  value##Left = left, value##Right = right,

How can I get similar result in Swift?

like image 601
John Difool Avatar asked Jun 20 '26 14:06

John Difool


1 Answers

Preprocessor directives are deliberately cut down to a very bare minimum in Swift. Even if technically possible, your particular case would go quite against Swift philosophy in respect of enums, as this philosopy requires that switch statements on enumerations are exhaustive, that is, cover all possible cases.

Now, if you would be able to dynamically fill up the enum's cases from some file, then how would compiler be able to ensure exhaustiveness? Opting out to use default: cases all over the program would basically throw the whole Swift's idea of enum safety right into the window.

If you stick with Swift then you are probably better off with dictionary as @RMenke suggests.

like image 145
0x416e746f6e Avatar answered Jun 23 '26 06:06

0x416e746f6e



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!