在过去的 Objective-C 时代,我经常将枚举用于具有常量内容的表格、分段控件等 - 在强制递增的整数列表从零开始的情况下。我还经常在末尾添加一个 ...count 成员以提供条目计数,这对表格部分和行很有用。尝试使用 swift 枚举来做到这一点被证明是很麻烦的——大量的原始值转换和开关中的额外默认子句以允许“计数”条目。任何人都可以建议一种处理此类情况的优雅方法吗?
最佳答案
自动增量在 Swift 中仍然可用。
enum Section: Int {
case A = 0
case B
case C
}
Section.C.rawValue // -> 2
至于count
,你应该手动实现它(如How do I get the count of a Swift enum?):
enum Section: Int {
case A = 0
case B
case C
static let count = C.rawValue + 1
}
至于“转换为原始值和额外的默认子句”问题,比较enum
而不是它的rawValue
。
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return Section.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .A: return 1
case .B: return 2
case .C: return 5
}
}
如果你想做类似array[Section.A]
的事情,你可以很容易地实现它。
extension Array {
subscript(section: Section) -> T {
return self[section.rawValue]
}
}
extension NSIndexPath {
convenience init(forRow row: Int, inSection section: Section) {
self.init(forRow: row, inSection: section.rawValue)
}
}
let array = ["foo", "bar", "baz"]
array[.B] // -> "bar"
let indexPath = NSIndexPath(forRow: 20, inSection: .C)
indexPath.section // -> 2
indexPath.row // -> 20
等等.. :)
关于ios - 快速替换旧式枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31557889/