首页 > 解决方案 > iOS Swift,枚举 CaseIterable 扩展

问题描述

我试图为枚举编写一个扩展,CaseIterable以便我可以获得原始值的数组而不是案例,但我不完全确定如何做到这一点

extension CaseIterable {

    static var allValues: [String] {
        get {
            return allCases.map({ option -> String in
                return option.rawValue
            })
        }
    }
}

我需要以某种方式添加 where 子句,如果我没有 where 子句,我会收到错误消息'map' produces '[T]', not the expected contextual result type '[String]'

任何人都知道是否有解决此问题的好方法?

我的枚举我希望这个函数看起来有点像这样

enum TypeOptions: String, CaseIterable {
    case All = "all"
    case Article = "article"
    case Show = "show"
}

标签: iosswift

解决方案


并非所有枚举类型都有关联RawValue的 ,如果有,则不一定是String

因此,您需要将扩展​​限制为枚举类型RawRepresentable,并将返回值定义为以下数组RawValue

extension CaseIterable where Self: RawRepresentable {

    static var allValues: [RawValue] {
        return allCases.map { $0.rawValue }
    }
}

例子:

enum TypeOptions: String, CaseIterable {
    case all
    case article
    case show
    case unknown = "?"
}
print(TypeOptions.allValues) // ["all", "article", "show", "?" ]

enum IntOptions: Int, CaseIterable {
    case a = 1
    case b = 4
}
print(IntOptions.allValues) // [1, 4]

enum Foo: CaseIterable {
    case a
    case b
}
// This does not compile:
print(Foo.allValues) // error: Type 'Foo' does not conform to protocol 'RawRepresentable'

推荐阅读