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.
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.
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 .
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.
A type that provides a collection of all of its values.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With