如何在Swift中使用枚举和switch()来处理UITableViewController?

5

我的UITableView有两个分区,因此我创建了一个枚举来表示它们:

private enum TableSections {
    HorizontalSection,
    VerticalSection
}

我应该如何在numberOfRowsInSection委托方法中使用传递的“section”变量进行切换?看起来我需要将“section”强制转换为我的枚举类型?还是有更好的方法可以实现这一点?

错误信息为“在类型'int'中找不到枚举类型'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
    }
}

您可以使用原始值。 - tktsubota
3个回答

6

杰夫·刘易斯做得很好,要详细说明并使代码更具准备性 -> 我处理这些事情的方式是:

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

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

  1. 使用switch语句处理区域类型

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


6
为此,您需要为枚举类型指定一个类型(在此示例中为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
    }
}

尽管 @tktsubota 指导了我正确的方向,但你提供了完整的答案。我会将这个标记为答案。谢谢。 - KevinS
1
关于命名规范的一个注释:“将枚举类型命名为单数而不是复数,以便它们读起来是不言自明的”,因此最好使用TableSection而不是TableSections作为枚举的名称(参见Swift编程语言指南)。 - Herre
@Herre 感谢你发现这个问题,我会进行编辑以显示更改。 - Jeff Lewis

4

好的,我已经搞清楚了,感谢@tktsubota指导我正确方向。我对Swift还比较陌生,但我查看了.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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接