iOS Swift,Enum CaseIterable扩展

Fon*_*nix 5 ios swift

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

extension CaseIterable {

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

我需要以某种方式添加一个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"
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 8

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

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

extension CaseIterable where Self: RawRepresentable {

    static var allValues: [RawValue] {
        return allCases.map { $0.rawValue }
    }
}
Run Code Online (Sandbox Code Playgroud)

例子:

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'
Run Code Online (Sandbox Code Playgroud)