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

186
Visualizações
Convert from switch case statement to a value in Swift

Maybe this is a stupid question

I have a switch case statement like this:

        self.text = type.rawValue
        switch type {
        case .teuro:
            self.backgroundColor =  UIColor.sapphireColor()
        case .lesson:
            self.backgroundColor = UIColor.orangeColor()
        case .profession:
            self.backgroundColor = UIColor.pinkyPurpleColor()
        }

Is there any way to write it in something like this example:

        self.backgroundColor = {
            switch type {
            case .teuro:
                return  UIColor.sapphireColor()
            case .lesson:
                return  UIColor.orangeColor()
            case .profession:
                return UIColor.pinkyPurpleColor()
            }
        }

Any comment or answer is appreciated. Thanks.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You are nearly there!

You've created a closure that returns a color, and are assigning it to a UIColor property, but a closure is not a color!

You just need to call (invoke) the closure to run it, so that it returns the color you want:

self.backgroundColor = {
    switch type {
    case .teuro:
        return  UIColor.sapphireColor()
    case .lesson:
        return  UIColor.orangeColor()
    case .profession:
        return UIColor.pinkyPurpleColor()
    }
}() // <---- notice the brackets!
over 4 years ago · Santiago Trujillo Relatório

0

Usually you don't wanna mix your models and your UI, and only need to use this colors inside one view

That's why I ended up creating such extensions, which are only accessible inside current file of the view:

private extension Type {
    var backgroundColor: UIColor {
        switch self {
        case .teuro:
            return .sapphireColor()
        case .lesson:
            return .orangeColor()
        case .profession:
            return .pinkyPurpleColor()
        }
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

Sweeper is absolutely correct, that you can initialize this with a closure by adding the missing () at the end. So that is the literal answer to your question.

But Philip also is correct, that it would be best to add an extension to your enumeration type to define a mapping between colors and your cases. It abstracts the color scheme from both the calling point (e.g. ensuring that you have a consistent application of colors throughout the app, while never repeating yourself), but at the same time, avoids entangling the UI color scheme with some basic enumeration type.

But I would like to take it a step further, namely to extend this observation to the text property, too. You should not use the rawValue strings in your UI. The raw codes (if you have them at all) should not be conflated with the strings you want to display in the UI. One is a coding question, while the other is a UI question.

So, I would not only move color into an extension, but also the display text, e.g. I would define a text property:

extension MyEnumerationType {
    var text: String { rawValue }
}

Then you could do:

self.text = myEnumerationInstance.text

Now here I am still using rawValue, but I am abstracting it away from the UI. The reason is that you might want to eventually support different strings, but not change your rawValue codes. E.g., you might want to support localization at some point:

extension MyEnumerationType {
    var text: String { NSLocalizedString(rawValue, comment: "MyEnumerationType") }
}

Or you might have a switch statement inside this text computed property. But it avoids the tight coupling of your enumeration’s internal representation (the rawValue) from the UI.

So, bottom line, not only should you abstract the color scheme out of the type itself, but you should abstract display text, too. That way, you can change your display text at some future date, but not break code that relied on the old rawValue values.

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