【发布时间】: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