Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

345
Visualizações
iOS Swift, Enum CaseIterable extension

Im trying to write an extension for an enum that is CaseIterable so that i can get an array of the raw values instead of the cases, Im not entirely sure how to do that though

extension CaseIterable {

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

i need to add a where clause somehow, if i dont have a where clause i get an error saying 'map' produces '[T]', not the expected contextual result type '[String]'

Anyone know if there is a good way of going about this?

my enums i want this function to work on look a bit like this

enum TypeOptions: String, CaseIterable {
    case All = "all"
    case Article = "article"
    case Show = "show"
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Not all enumeration types have an associated RawValue, and if they have then it is not necessarily a String.

Therefore you need to restrict the extension to enumeration types which are RawRepresentable, and define the return value as an array of RawValue:

extension CaseIterable where Self: RawRepresentable {

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

Examples:

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'
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda