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