swift - Is it possible to change an associated value within an enum? -


i'm playing around swift enums , wondering if there way change assoicated value of enum such code below attempts fails.

enum myenum {     case somecase(int?)      mutating func somefunc() {         switch self {         case .somecase(let a):             if != nil {                 // = 5 can't of course assigning let                 var temp = a!; // generates warning                 temp = 5;             }         }     } } 

if isn't possible, when mutating enums come xcode?

rob napier's answer fine have different understanding of question. have written instead:

enum myenum {      case somecase(int?)      mutating func somefunc() {         switch self {         case .somecase(.some(_)):              self = .somecase(5)         default:          // or case .somecase(.none): if prefer             break         }     }  } 

with code, enum mutated somefunc if , if associated value not nil. thus, have following results while testing in playground (results appear comments):

var x = myenum.somecase(nil)  switch x { case .somecase(.some(let a)):     println(a) default:     println("associated value nil") // print "associated value nil" }  x = myenum.somecase(20) x.somefunc()  switch x { case .somecase(.some(let a)):     println(a) // print 5 default:     println("associated value nil") } 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -