swift2 - How to Don't Repeat Yourself with Swift 2.0 enums -


i've got multiple enums raw values, don't having rawvalue: every time initialize 1 raw value, i've supplied alternative delegating initializer no external label:

enum e1 : int {     case one, 2     init?(_ what:int) {         self.init(rawvalue:what)     } } enum e2 : int {     case one, 2     init?(_ what:int) {         self.init(rawvalue:what)     } } 

very nice. can let e = e1(0) , right thing happens.

now i'd consolidate repeated code. hoping swift 2.0 protocol extensions allow me - writing init?(_ what:int) initializer in one place , injecting / inheriting in both enums. however, haven't found way works. problem protocol extension doesn't know adopter have init(rawvalue:) initializer, , have not found way reassure it.

i suspect because of automagic way rawvalue initializer comes existence, , nothing can done. perhaps has suggestion.

sounds you're looking extend rawrepresentable protocol:

extension rawrepresentable {     init?(_ what: rawvalue) {         self.init(rawvalue: what)     } } 

any enum raw type automatically conforms rawrepresentable, therefore haven't got make e1 or e2 conform protocols:

enum e1: int {     case 1 = 1, 2 }  enum e2: string {     case 1 = "1", 2 = "2" }  let e1 = e1(1)   // .one let e2 = e2("2") // .two 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -