Writing a simple enum in Swift 2 like I can in Java -


in java, can create enum takes integer follows:

public enum myenum {     foo(1), bar(4), baz(8);      private     int value;      myenum(int value) {         this.value = value;     }      public     int getvalue() {         return value;     } } 

how do same in swift (version 2.0)? guess was:

public enum myenum {     case foo(1)     case bar(4)     case baz(8)      public     let value: int      init(value: int) {         self.value = value     } } 

but attempting compile gives following errors:

expected type expected ',' separator expected type expected ',' separator expected type expected ',' separator enums may not contain stored properties 

(the first 2 on line "case foo(1)", second 2 on "case bar(4)", third 2 on "case baz(8)" , final error on line "let value: int")

how can fix swift code create enum equivalent 1 in java?

many thanks

 public   enum myenum: int {     case foo = 1     case bar = 4     case baz = 8   }    var foo = myenum(rawvalue: 4)   var rawvalue = foo?.rawvalue 

in swift there's no need constructor/getter of underlying value. included in enum types (as rawvalue, of type enum inherits from)

also, note constructor takes in rawvalue failable (i.e. returns optional), it's possible pass in rawvalue doesn't map myenum


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -