我有一个名为 TableViewItem
的协议(protocol)。此协议(protocol)强制符合要求的对象实现 type
属性,该属性的类型为 TableViewCellIdentifiable
协议(protocol)。 TableViewCellIdentifiable
用于将三个嵌套的枚举组合在一起,如下所示:
internal protocol TableViewCellIdentifiable: Equatable { }
internal enum TableViewCellType {
internal enum PortfolioSelection: String, TableViewCellIdentifiable {
case portfolio = "portfolioTableViewCell"
case enterPortfolioDetails = "enterPortfolioDetailsTableViewCell"
case addPortfolio = "actionTableViewCell"
}
internal enum EditPortfolio: String, TableViewCellIdentifiable {
case editPortfolioName = "editPortfolioNameTableViewCell"
case deletePortfolio = "deletePortfolioTableViewCell"
}
internal enum Portfolio: String, TableViewCellIdentifiable {
case portfolioAsset = "portfolioAssetTableViewCell"
case addAsset = "actionTableViewCell"
}
}
这是一个如何使用它的例子:
internal final class EditPortfolioNameTableViewItem: TableViewItem {
// MARK: - Internal Properties
internal let type: TableViewCellIdentifiable = TableViewCellType.EditPortfolio.editPortfolioName
internal let viewModel: TableViewCellModel
// MARK: - Initialization
internal init(viewModel: EditPortfolioNameTableViewCellModel) {
self.viewModel = viewModel
}
}
不幸的是,在声明 type
属性的那一行,我收到以下错误:
Protocol 'TableViewCellIdentifiable' can only be used as a generic constraint because it has Self or associated type requirements
我已经通读了遇到此错误的其他人的其他问题/答案,但我不太明白为什么这个特定的实现有问题,以及解决方案是什么。我知道 Equatable
是问题的根源,但这对功能至关重要,因为枚举有两个目的:
- 为表格 View 单元格(原始值)提供重用标识符。
允许比较类型 - 即:
self.tableViewItems.contains(where: { $0.type == item.type })
任何建议将不胜感激,即使这意味着采取替代方法。
最佳答案
在你的脑海中,下面的代码应该编译吗?
var x : Equatable
不应该。为什么?
因为如果你有:
var x : Equatable
var y : Equatable
那么编译器就不能确保 x & y 是同一类型。 x
可以是“John”,因为“John”/字符串是可相等的...而 y
可以是 10
,因为 10/整数是平等的。
并且编译器会怀疑下面几行你可能想要做
if x == y { print ("equal" }
它无法处理。所以它只是阻止你从一开始就这样做。
由于上述原因,您的代码的以下行将触发相同的错误。
internal let type: TableViewCellIdentifiable = TableViewCellType.EditPortfolio.editPortfolioName
关于swift - 符合 Equatable 协议(protocol)的嵌套枚举产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55012529/