【问题标题】:Encountering issues when using a protocol based Enum使用基于协议的 Enum 时遇到的问题
【发布时间】:2019-12-30 19:52:59
【问题描述】:

我目前拥有的简化版本,取自我设置的 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 的两个地方都提供以下错误:

Protocol 'MyProtocol' 只能用作通用约束,因为 它有 Self 或关联的类型要求

然后我将其切换为以下内容,消除了错误,但产生了一个新问题:

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

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

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

我需要能够访问MyProtocol 中定义的属性,但是这两种方法都不适合我,而且我已经没有想法了。

【问题讨论】:

    标签: swift enums swift-protocols


    【解决方案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
        }
    }
    

    【讨论】:

    • 完美,实际上我刚才也得到了相同的解决方案,并且也会使用您的计数建议!
    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 2011-03-19
    • 2013-08-08
    • 1970-01-01
    相关资源
    最近更新 更多