开发者社区> 问答> 正文

获取所有枚举值作为数组

我有以下列举。

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 { return EstimateItemStatus(id: n++)!.description } ) } 但我收到以下错误。

无法找到类型'GeneratorOf'的初始化程序,该初始化程序接受类型'(()-> _)'的参数列表

我不知道如何解决这个问题。有什么帮助吗?或者,请告诉我是否有更简单/更好/更优雅的方式来做到这一点。

谢谢。 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-08 19:21:57 495 0
1 条回答
写回答
取消 提交回答
  • 对于Swift 4.2(Xcode 10)及更高版本 有一个CaseIterable协议:

    enum EstimateItemStatus: String, CaseIterable { case pending = "Pending" case onHold = "OnHold" case done = "Done"

    init?(id : Int) {
        switch id {
        case 1: self = .pending
        case 2: self = .onHold
        case 3: self = .done
        default: return nil
        }
    }
    

    }

    for value in EstimateItemStatus.allCases { print(value) } 对于Swift <4.2 不,您无法查询enum包含的值。看到这篇文章。您必须定义一个列出所有值的数组。另请查看Frank Valbuena的聪明解决方案。

    enum EstimateItemStatus: String { case Pending = "Pending" case OnHold = "OnHold" case Done = "Done"

    static let allValues = [Pending, OnHold, Done]
    
    init?(id : Int) {
        switch id {
        case 1:
            self = .Pending
        case 2:
            self = .OnHold
        case 3:
            self = .Done
        default:
            return nil
        }
    }
    

    }

    for value in EstimateItemStatus.allValues { print(value) }

    2020-02-08 19:22:11
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载