ios - 快速替换旧式枚举

标签 ios macos swift enums

在过去的 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/

相关文章:

macos - 如何让 OSX 上的 WebView(或 WKWebView)在 Mojave 中采用深色模式

ios - 无延迟播放音效

javascript - 防止 iOS 键盘在 cordova 3.5 中滚动页面

ios - 如何在模态呈现的 viewController 中获取 UIView 的位置

java - 如何设置从我的 Java 应用程序启动的 MacOS 应用程序包的工作目录?

ios - 文档文件夹内容 - 文件无法打开,因为没有这样的文件

ios - 当用户点击屏幕上的任意位置时调用函数

objective-c - 使用 [NSString stringWithString : @"some string"] versus @"some string" 的优缺点

ios - 当两个 ViewController 打开时,如何在两个 ViewController 中接收相同的回调?

java - 了解不同版本的 Java 在 Mac OS 上的共存