使用基于协议的枚举

时间:2019-12-30 19:52:59

标签: swift enums swift-protocols

从我设置的Playground文件中获取的当前版本的简化版本:

import Foundation
/// Simplified protocol here
protocol MyProtocol: CaseIterable {
    static var count: Int { get }

    var name: String { get }
}
/// Simplified extension. This works fine with app
extension MyProtocol {
    static var count: Int {
        return Self.allCases.count
    }
}
/// Simplified enum, this works fine as well
enum MyEnum: MyProtocol {
    case value

    var name: String {
        return "name"
    }
}

按预期使用以下作品:

print(MyEnum.count) // 1
let myEnum = MyEnum.value
print(myEnum.name) // name

但是,我想创建一个用MyEnum初始化的对象。

首先,我尝试了以下操作:

final class MyManager {
    private let myEnum: MyProtocol

    init(myEnum: MyProtocol) {
        self.myEnum = myEnum
    }
}

但是,我使用MyProtocol的两个地方都出现以下错误:

  

协议“ MyProtocol”只能用作通用约束,因为   有自我或相关类型要求

然后我用消除错误的以下内容进行了切换,但产生了新问题:

final class MyManager<MyProtocol> {
    private let myEnum: MyProtocol

    init(myEnum: MyProtocol) {
        self.myEnum = myEnum
    }
}

当我尝试访问myEnum的属性时,它们没有出现在Xcode中:

enter image description here

我需要能够访问MyProtocol中定义的属性,但是这两种方法都不适合我,我的想法也用光了。

1 个答案:

答案 0 :(得分:1)

MyProtocol泛型与MyProtocol协议不同。您需要像这样的东西

final class MyManager<MyP: MyProtocol> {
    private let myEnum: MyP

    init(myEnum: MyP) {
        self.myEnum = myEnum
        print(myEnum.name)
    }
}

我还想指出,实现count的更好方法是扩展CaseIterable

extension CaseIterable {
    static var count: Int {
        return Self.allCases.count
    }
}