.color from String in Array

I’m looking at the Guidebook app and wanted to use a field in the array (Cities of the Struct City) which also has a nested array of Attractions. I’ve added a color attribute to the dataservice for City which fetches fine in logic within the ForEach whether in CityView or CityCard as I’m fetching strings to display on the ZStack of the rectangle. But inside of a shape as an example

.foregroundColor(city.color) OR cities.color depending on which level of View I’m working in.
I understand it’s compiled code but I’ve hardcoded the switch as such.

switch city.color {
case ‘cyan’:
case ‘magenta’:
case ‘pink’:
case ‘blue’:
case ‘brown’:

This doesn’t work although getting the string from city.color works in the same place. I’ve scoured the internet and just not sure what I need to do to turn the string from the array representing the color into something I can utilize in the Case Switch to modify the shape depending on which array element has for the value of the color attribute.

Any help appreciated

Hi Edward,

Welcome to the community.

Sorry it’s taken so long to get back to you. Some of us are a bit time poor at the moment.

Try this approach.

Create a function in your app that takes a string with the color name and returns a Color

    func getColor(cityColor: String) -> Color {
        var selectedColor: Color = .clear
        switch cityColor {
        case "cyan":
            selectedColor = Color.cyan
        case "magenta":
            selectedColor = Color.red
        case "pink":
            selectedColor = Color.pink
        case "blue":
            selectedColor = Color.blue
        case "brown":
            selectedColor = Color.brown
        return selectedColor

By the way, in SwiftUI there is no color named “magenta” so you are best to use “red”. There is a UIColor named “magenta” but I would not mix the two since you will need to handle them differently and that just over complicates things.

Anyway in order to use the color in your App, you would do this:

.foregroundColor(getColor(cityColor: city.color))

See how you go. Get back to me if there is anything you are not clear on.

Chris I’ll try that as it seems something to learn. For now of course as soon as I went back to the videos on this site I found this allowing essentially the same logic in the Rectangle props directly

 Rectangle() .foregroundColor(city.color == "cyan" ? .cyan : city.color == "blue" ? .blue : city.color == "brown" ? .brown : city.color == "pink" ? .pink : city.color == "teal" ? .teal : .red)

and I did move Magenta to Teal. I’m also looking at the color assets and avoid UISwift.