【发布时间】:2016-01-02 07:47:53
【问题描述】:
我有以下枚举。
enum EstimateItemStatus: Printable {
case Pending
case OnHold
case Done
var description: String {
switch self {
case .Pending: return "Pending"
case .OnHold: return "On Hold"
case .Done: return "Done"
}
}
init?(id : Int) {
switch id {
case 1:
self = .Pending
case 2:
self = .OnHold
case 3:
self = .Done
default:
return nil
}
}
}
我需要将所有原始值作为字符串数组获取(例如["Pending", "On Hold", "Done"])。
我将此方法添加到枚举中。
func toArray() -> [String] {
var n = 1
return Array(
GeneratorOf<EstimateItemStatus> {
return EstimateItemStatus(id: n++)!.description
}
)
}
但我收到以下错误。
找不到接受类型为“(() -> _)”的参数列表的“GeneratorOf”类型的初始化程序
有没有更简单、更好或更优雅的方法来做到这一点?
【问题讨论】:
-
你可以像 let array 一样创建数组:[EstimateItemStatus] = [.Pending, .Onhold, .Done]
-
@KristijanDelivuk 我想将此功能添加到枚举本身。因此,如果我向枚举添加另一个值,我不必在代码库的其他地方到处添加它。
-
我有一个答案你可以参考这里stackoverflow.com/a/48960126/5372480