我目前拥有的简化版本,取自我设置的 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”只能用作通用约束,因为它具有 Self 或关联的类型要求
然后,我使用以下方法将其切换为消除错误的方法,但产生了一个新问题:
final class MyManager<MyProtocol> {
private let myEnum: MyProtocol
init(myEnum: MyProtocol) {
self.myEnum = myEnum
}
}
当我尝试访问 的属性时myEnum
,它们不会出现在 Xcode 中:
我需要能够访问 中定义的属性MyProtocol
,但是这两种方法都不适用于我并且我已经没有想法了。