swift - 符合 Equatable 协议(protocol)的嵌套枚举产生错误

标签 swift enums

我有一个名为 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 是问题的根源,但这对功能至关重要,因为枚举有两个目的:

  1. 为表格 View 单元格(原始值)提供重用标识符。
  2. 允许比较类型 - 即:

    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/

相关文章:

c# - Enum.TryParse - 它是线程安全的吗?

objective-c - Objective-C 中有类似 Java 枚举的东西吗?

ios - 动态 UITextView 错位行为

swift - 可选值和默认值需要使用默认初始值设定项进行初始化

ios - 如何使用自动布局动态更改 super View 的高度

c# - 使用泛型实现类型安全的枚举模式

postgresql - 将 int 列升级为 postgresql 中的枚举类型

c# - 具有基础类型的枚举。无意中返回字符串表示

ios - Swift:递归值类型

swift - 模拟器工作但再次呈现 UiViewController 时设备崩溃