Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift integer type cast to enum

Tags:

enums

ios

swift

I have enum declaration.

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

And use it in a method:

func performOperation(operation: OP_CODE) {

}

We all know that how we can call this normally

self.performOperation(OP_CODE.addition)

But if I have to call it in some delegate where integer value is not predictable than how to call it.

For example:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
     self.delegate.performOperation(indexPath.row)
}

Here, Compiler throws an error Int is not convertible to 'OP_CODE'. Tried here many permutations. But not able to figure it out.

like image 221
Kampai Avatar asked Nov 27 '14 10:11

Kampai


People also ask

What is Rawvalue in Swift?

Enumerations in Swift are much more flexible, and don't have to provide a value for each case of the enumeration. If a value (known as a raw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.

Is enum value type in Swift?

In Swift there are two categories of types: value types and reference types. A value type instance keeps a unique copy of its data, for example, a struct or an enum . A reference type, shares a single copy of its data, and the type is usually a class .

What is enumerated () in Swift?

enumerated()Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

What is Caseiterable in Swift?

A type that provides a collection of all of its values.


1 Answers

You need to specify the raw type of the enumeration

enum OP_CODE: Int {
    case addition, substraction, multiplication, division
}

addition will have a raw value of 0, substraction of 1, and so on.

and then you 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 an older version of swift, raw enumerations work a bit different. In Xcode < 6.1, you have to use fromRaw() instead of a failable initializer:

let code = OP_CODE.fromRaw(indexPath.row)
like image 181
Gabriele Petronella Avatar answered Nov 11 '22 05:11

Gabriele Petronella