Swift enum loses initialized values when set as a property? -


i've found work-around, problem vexing me , thought i'd share in case else having same problem. love know why happening. in code below, can switch on enum fine during class initializer when it's local variable. store enum value property. when try switch on stored property (named foo) in different method (named bar()) in example below - compiler warnings , error member(s) not recognized. seems know foo myenum type, doesn't know .abc, .def, , .ghi members.

 enum myenum {     case abc, def, ghi }  class myclass : nsobject {      var foo : myenum!      convenience init(foo: myenum) {          self.init()          self.foo = foo          switch foo {          case .abc: println("abc foo")         case .def: println("def foo")         case .ghi: println("ghi foo")         default: println("no foo")          }     }      func bar() {          switch foo {          case .abc: println("abc foo")         case .def: println("def foo")         case .ghi: println("ghi foo")         default: println("no foo")          }     } } 

the workaround either say:

switch foo myenum { }

or declare local variable in method like

let x : myenum = foo  switch x {  }

again, glad found workaround, sure know if expected behavior or if radar needs filed apple. xcode 6.2, btw.

property foo not myenum, implicitlyunwrappedoptional<myenum> aka myenum!. unlike many other cases, switch not implicitly unwrap it.

you have unwrap manually:

    if let foo = foo {         switch foo {         case .abc: println("abc foo")         case .def: println("def foo")         case .ghi: println("ghi foo")         default: println("no foo")         }     }     else {         println("nil foo")     } 

or force unwrap ! if sure foo not nil, :

    switch foo! {     case .abc: println("abc foo")     case .def: println("def foo")     case .ghi: println("ghi foo")     default: println("no foo")     } 

or match implicitlyunwrappedoptional<enum> is:

    switch foo {     case .some(.abc): println("abc foo")     case .some(.def): println("def foo")     case .some(.ghi): println("ghi foo")     default: println("no foo")     } 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -