覆盖子类中的枚举大小写



我有一个声明枚举的 Swift 文件,我在文件中定义的类中的函数中使用它:

class EnumTableViewController: UITableViewController {
enum SectionType {
case undefined
}
public func sectionType(for sectionNumber: Int) -> SectionType {
...
}
}

我想从这个类衍生出来并覆盖后代中的枚举(我的每个后代都需要不同的功能,所以枚举的值必须是唯一的(,并且仍然能够调用超类的辅助方法。

class ExampleTableViewController: EnumTableViewController {
enum SectionType {
case undefined
case first
case second
case third
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionType = self.sectionType(for: section)
...
}
}

在 Objective-C 中,我可以像上面设想的那样简单地覆盖枚举,但据我所知,在 Swift 中没有办法改变或覆盖它。显然我需要其他解决方案,但我不知道要寻找什么。

有两件事对我来说很重要:1.能够使用枚举功能(如选项卡完成和切换案例(和2.具有相同的函数,这些函数仅在一个位置将此枚举作为参数,而无需在每个类中重复它们。

在Sweeper的帮助下,解决方案似乎是类似的:

protocol EnumTableViewController: UITableViewController {
associatedtype SectionType
}
extension EnumTableViewController {
func sectionType(for sectionNumber: Int) -> SectionType? {
...
}
}
class ExampleTableViewController: UITableViewController, EnumTableViewController {
typealias SectionType = ExampleSectionType
enum ExampleSectionType {
case first
case second
...
}
}

所以基本上我不得不将EnumTableViewController的功能拆分为一个协议(无论如何都更适合(和一个UITableViewController扩展。由于协议无法知道后代的枚举实现,因此我不得不使用associatedtype而不是任何具体类型。

最新更新