如何在Swift中使用enum和switch()与UITableViewController
我的UITableView有两个部分,所以我为他们创build了一个枚举:
private enum TableSections { HorizontalSection, VerticalSection }
如何使用在numberOfRowsInSection委托方法中传递的“section”var进行切换? 看来我需要将“部分”投给我的枚举types? 还是有更好的方法来完成这个?
错误是“Enum case”HorizontalSection“not found in type'int'。
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case .HorizontalSection: return firstArray.count case .VerticalSection: return secondArray.count default return 0 } }
为了做到这一点,你需要给你的枚举types(Int在这种情况下):
private enum TableSection: Int { horizontalSection, verticalSection }
这使得'horizontalSection'将被赋值为0,'verticalSection'将被赋值为1。
现在在你的numberOfRowsInSection
方法中,你需要在enum属性上使用.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指出我正确的方向。 我对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 } }
杰夫·刘易斯做得对,详细说明并给代码更多的准备 – >我处理这些事情的方式是:
- 使用原始值 – >部分索引实例化枚举
guard let sectionType = TableSections(rawValue: section) else { return 0 }
- 使用与部分types的开关
switch sectionType { case .horizontalSection: return firstArray.count case .verticalSection: return secondArray.count }