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
Post a Comment