具有通用枚举的Swift Struct属性

时间:2019-11-13 07:31:46

标签: swift enums

我当前正在创建设置页面。我试图动态地将枚举分配给我的struct属性。 我要实现的是,每当调用Settings结构时,它将自动将所有各自的设置附加在一起。以下是枚举

protocol BaseSettings {}

enum SettingsCategory: String, CaseIterable {
    case sales = "Sales"
    case payment = "Payment"
}

struct SettingsSection {
    var settingsNameArray: [BaseSettings]
    var settingsCategoryName: SettingsCategory

    init(settingsCategory: SettingsCategory) {
        self.settingsCategoryName = settingsCategory

        switch settingsCategory {
        case .sales:
            self.settingsNameArray = SalesSettings.allCases
        case .payment:
            self.settingsNameArray = PaymentSettings.allCases
        }
    }
}

struct Settings {
    var sections = [SettingsSection]()

    init() {
        for eachSettingCategory in SettingsCategory.allCases {
            self.sections.append(SettingsSection(settingsCategory: eachSettingCategory))
        }
    }
}

enum SalesSettings: String, BaseSettings, CaseIterable {
    case testSettings = "Test Sales Settings"
}

enum PaymentSettings: String, BaseSettings, CaseIterable {
    case testSettings = "Test Payment Settings"
}

以上代码工作正常。设置按部分分组。但是,当我想填充每个枚举实例的String原始值时,我面临一个问题。由于协议BaseSettings不是枚举,所以我无法获得rawValue

 let settingsDataSource = SettingsConstant.Settings()
 let settingsName = settingsDataSource.sections[indexPath.section].settingsNameArray[indexPath.row]
    cell.textLabel?.text = "\(settingsName)"

tableView不是显示每个枚举案例的rawValue,而是显示每个枚举案例。

如何修复此数据结构?谁能指导我?

谢谢

1 个答案:

答案 0 :(得分:0)

在协议声明中指定您需要原始值!

protocol BaseSettings {
    var rawValue: String { get }
}

SalesSettings这样的枚举将自动符合此新要求,因为当RawRepresentable.rawValueRawValue时,它与String完全相同。