Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda