我有一個枚舉與幾個案例,我用於計算,用戶將能夠設置一個作爲他們的偏好。他們當然需要能夠改變這種偏好,所以我想在一個表格視圖中顯示它們,以便他們可以看到它們並選擇他們想要設置的偏好。如何使用cellForRowAtIndexPath中的枚舉來填充tableView單元格?
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()
}
}
}
的問題是,一個枚舉不具有indexPath所以我不能遍歷它,並抓住這些案例名稱:
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
}
我能想出的最好的是創造這些案例的數組,並用它來創建單元格:
let Calculation = [Calculation1, Calculation2, Calculation3 ...etc]
哪些工作,但顯然是一個醜陋的黑客。
有沒有更好的方法來做到這一點?
你爲什麼要這樣做,而不是使用「計算」結構的「數組」? – Fogmeister
黑客只是看起來很醜,因爲你開始時用一種非常糟糕和醜陋的方式來枚舉枚舉值。每當你用名字列舉一些變量時,就會出現錯誤。給他們有意義的名字或者首先使用數組。 – luk2302
爲什麼不使用switch語句來檢查不同的枚舉情況? – NSGangster