如何在Swift中将enum和switch()与UITableViewController一起使用



我的UITableView有两个部分,所以我为它们创建了一个枚举:

private enum TableSections {
    HorizontalSection,
    VerticalSection
}

如何切换numberOfRowsInSection委托方法中传递的"section"var?似乎我需要将"section"强制转换为我的枚举类型?或者有更好的方法来实现这一点吗?

错误是在类型'int'中找不到"Enum case"HorizontalSection"。

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section {
    case .HorizontalSection:
        return firstArray.count
    case .VerticalSection:
        return secondArray.count
    default 
        return 0
    }
}

为了做到这一点,您需要给您的枚举一个类型(在这种情况下为Int):

private enum TableSection: Int {
    horizontalSection,
    verticalSection
}

这使得"horizontalSection"将被分配值0,"verticalSection"将分配值1。

现在,在numberOfRowsInSection方法中,您需要对枚举属性使用.rawValue,以便访问它们的整数值:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section {
    case TableSection.horizontalSection.rawValue:
        return firstArray.count
    case TableSection.verticalSection.rawValue:
        return secondArray.count
    default:
        return 0
    }
}

Jeff Lewis做得很好,为了详细说明这一点,并让代码更加准备就绪->我处理这些事情的方法是:

  1. 使用原始值实例化枚举->节索引

guard let sectionType = TableSections(rawValue: section) else { return 0 }

  1. 使用分段类型的开关

switch sectionType { case .horizontalSection: return firstArray.count case .verticalSection: return secondArray.count }

好吧,我想通了,谢谢@tktsubota为我指明了正确的方向。我对斯威夫特很陌生。我查看了.rawValue并做了一些更改:

private enum TableSections: Int {
    case HorizontalSection = 0
    case VerticalSection = 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section {
    case TableSections.HorizontalSection.rawValue:
        return firstArray.count
    case TableSections.VerticalSection.rawValue:
        return secondArray.count
    default 
        return 0
    }
}

最新更新