最近我在一个应用中处理同类情况的方式是使用完全由静态成员组成的结构体,而不是枚举——其中一部分原因是我有更多的信息要与每个选项关联,另一部分原因是我厌倦了到处调用
toRaw()
和
fromRaw()
,还有一部分原因是(正如你发现的那样)当无法循环或获取完整列表时,枚举失去了优势。
因此,我做的是这样的:
struct Sizes {
static let Easy = "Easy"
static let Normal = "Normal"
static let Hard = "Hard"
static func sizes () -> [String] {
return [Easy, Normal, Hard]
}
static func boardSize (s:String) -> (Int,Int) {
let d = [
Easy:(12,7),
Normal:(14,8),
Hard:(16,9)
]
return d[s]!
}
}
struct Styles {
static let Animals = "Animals"
static let Snacks = "Snacks"
static func styles () -> [String] {
return [Animals, Snacks]
}
static func pieces (s:String) -> (Int,Int) {
let d = [
Animals:(11,110),
Snacks:(21,210)
]
return d[s]!
}
}
现在我们来到
cellForRowAtIndexPath
,我可以这样说:
let section = indexPath.section
let row = indexPath.row
switch section {
case 0:
cell.textLabel.text = Sizes.sizes()[row]
case 1:
cell.textLabel.text = Styles.styles()[row]
default:
cell.textLabel.text = ""
}
本质上,我只是将这两个结构体用作具有一定智能的名称空间。我并不是说这比你正在做的更好;它们都是非常符合Swift语言特点的。这只是另一个值得考虑的想法。