ios - Swift integer type cast to enum -


i have enum declaration.

enum op_code {     case addition     case substraction     case multiplication     case division } 

and use in method:

func performoperation(operation: op_code) {  } 

we know how can call normally

self.performoperation(op_code.addition) 

but if have call in delegate integer value not predictable how call it.

for example:

func tableview(tableview: uitableview, didselectrowatindexpath indexpath: nsindexpath) {      self.delegate.performoperation(indexpath.row) } 

here, compiler throws error int not convertible 'op_code'. tried here many permutations. not able figure out.

you need specify raw type of enumeration

enum op_code: int {     case addition, substraction, multiplication, division } 

addition have raw value of 0, substraction of 1, , on.

and can do

if let code = op_code(rawvalue: indexpath.row) {     self.delegate.performoperation(code) } else {    // invalid code } 

more info here: https://developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/enumerations.html#//apple_ref/doc/uid/tp40014097-ch12-xid_222


for older swift releases

in case you're using older version of swift, raw enumerations work bit different. in xcode < 6.1, have use fromraw() instead of failable initializer:

let code = op_code.fromraw(indexpath.row) 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

qt - How to embed QML toolbar and menubar into QMainWindow -