[英]Swift replacement for old style enums
Back in the old Objective-C days I would often use enums for things like tables with constant contents, segmented controls, etc - in situations where there was an enforced incremented list of integers starting at zero. 在过去的Objective-C时代,我经常将枚举用于具有恒定内容的表,分段控件等的东西-在存在从零开始的强制增量列表的情况下。 I would also often add a ...count member at the end to give a count of the entries, useful for table section & rows.
我还经常在末尾添加一个... count成员,以对条目进行计数,这对于表部分和行很有用。 Trying to do this with swift enums is proving troublesome - lots of conversions to & from raw values and extra default clauses in switches to allow for the 'count' entry.
试图用快速枚举来做到这一点很麻烦-大量转换为原始值和从原始值到转换的转换,并在开关中添加了额外的默认子句以允许输入“ count”。 Can anyone suggest a graceful method of dealing with these sorts of situations?
谁能建议一种应对此类情况的优雅方法?
Automatic increment is still available in Swift. 自动递增在Swift中仍然可用。
enum Section: Int {
case A = 0
case B
case C
}
Section.C.rawValue // -> 2
As for count
, you should implement it manually (as How do I get the count of a Swift enum? ): 至于
count
,您应该手动实现它(如我如何获取Swift枚举的计数? ):
enum Section: Int {
case A = 0
case B
case C
static let count = C.rawValue + 1
}
As for "conversions to & from raw values and extra default clauses" problem, compare with enum
instead of its rawValue
. 至于“与原始值和额外的默认子句之间的转换”问题,请与
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
}
}
If you want to do something like array[Section.A]
, you can easily implement it. 如果您想执行
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
And so on.. :) 等等.. :)
Add a function "count" to each enum. 向每个枚举添加函数“ count”。 For example
例如
static func count() -> Int { return 3 }
Integer -> enum conversion is done by the init method. 整数->枚举转换是通过init方法完成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.