Home > Enterprise >  Computed Property
Computed Property

Time:11-29

I have this code and there is a problem in it I need to determain the colour name based on the value of the red , the green and the blue value using structure and computed properties.

struct Colour {
  var red:Int
  var green:Int
  var blue:Int
  var colourName: String
  var chosenColour: String {
    return "The colour is \(colourName)"
  }
}
 
var colour = Colour(red:255 , green:255 , blue:255, 

colourName:"White" )
print(colour.chosenColour)

How can I fix it?

CodePudding user response:

A computed property calculates its value depending on other values (in the object).

An efficient solution is a switch statement

struct Colour {
    var red: Int
    var green: Int
    var blue: Int
    var colourName: String
    var chosenColour: String {
        switch (red, green, blue) {
            case (255, 255, 255): return "White"
            case (0, 0, 0): return "Black"
            case (255, 0, 0): return "Red"
            case (0, 255, 0): return "Green"
            case (0, 0, 255): return "Blue"
            default: return "Mixed Colour"
        }
    }
}
 
  • Related