I have an enum with several cases that I'm using for calculations and the user will be able to set one as their preference. They of course need to be able to change that preference so I want to show these in a table view so they can see them all and choose the one they want to set as their preference.
enum Calculation: Int {
case Calculation1
case Calculation2
case Calculation3
case Calculation4
case Calculation5
case Calculation6
case NoChoice // this exist only for the little trick in the refresh() method for which I need to know the number of cases
// This static method is from http://stackoverflow.com/questions/27094878/how-do-i-get-the-count-of-a-swift-enum/32063267#32063267
static let count: Int = {
var max: Int = 0
while let _ = Calculation(rawValue: max) { max += 1 }
return max
}()
static var selectedChoice: String {
get {
let userDefaults = NSUserDefaults.standardUserDefaults().objectForKey("selectedCalculation")
if let returnValue = userDefaults!.objectForKey("selectedCalculation") as? String {
return returnValue // if one exists, return it
} else {
return "Calculation1" // if not, return this default value
}
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "selectedCalculation")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
}
The problem is that an enum doesn't have an indexPath so I can't iterate through it and grab those case names:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("formulaCell", forIndexPath: indexPath)
// Configure the cell...
let currentFormula = Calculation[indexPath.row] <- Error: Type 'Calculation.Type' has no subscript members
cell.textLabel?.text = currentFormula
return cell
}
The best I could come up with is to create an array of those cases and use it to create the cells:
let Calculation = [Calculation1, Calculation2, Calculation3 ...etc]
which worked but is clearly an ugly hack.
Is there a better way to do this?