我有枚举声明.
enum OP_CODE { case addition case substraction case multiplication case division }
func performOperation(operation: OP_CODE) { }
我们都知道我们如何正常地称之为
self.performOperation(OP_CODE.addition)
但是如果我必须在某个委托中调用它,其中整数值不可预测而不是如何调用它.
例如:
func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) { self.delegate.performOperation(indexPath.row) }
解决方法
您需要指定枚举的原始类型
enum OP_CODE: Int { case addition,substraction,multiplication,division }
添加的原始值为0,减法为1,依此类推.
然后你就可以做到
if let code = OP_CODE(rawValue: indexPath.row) { self.delegate.performOperation(code) } else { // invalid code }
对于较旧的快速发布
如果您使用的是较旧版本的swift,原始枚举的工作方式会有所不同.在Xcode< 6.1,你必须使用fromraw()而不是一个可用的初始化器:
let code = OP_CODE.fromraw(indexPath.row)