Protocol 'Any' as a type cannot conform to 'ShapeStyle'?

Hello! I'm a beginner with swift, and I'm trying to make a wordle solver for iPhone. So far, I've been able to make a 5x6 grid of 30 rectangles where the letters will go, and I want to be able to change the color of each letter by tapping on it. However, I'm running into an error that only appears when I have the code that changes the color of the rectangle. The error message reads: " Protocol 'Any' as a type cannot conform to 'ShapeStyle' ", and the error is on the RoundedRectangle... line. I can't figure out how to fix this.
Here's the code:

struct ContentView: View {                             // (vvv Current color, number of times clicked)
    @State private var letterColors = Array(repeating: [Color.black, 0], count: 30)
    @State private var colors = [Color.black, Color.yellow, Color.green]
    var columns: [GridItem] = Array(repeating: GridItem(.flexible()), count: 5)
    var body: some View {
        VStack{
            LazyVGrid(columns: columns){
                ForEach((0...29), id: \.self) { i in
                        RoundedRectangle(cornerRadius: 20, style: .continuous)
                            .fill(letterColors[i][0])
                            .shadow(radius: 10)
                            .frame(width: 70, height: 70)
                            .onTapGesture {
                                letterColors[i][1] += 1
                                letterColors[i][0] = colors[letterColors[i][1] as! Int % 3]
                            }
                    }
            }
            Spacer()
        }
    }
}

.fill(...) takes a ShapeStyle, change your colors:

colors = [ShapeStyle.black, .yellow, .green]

and see?

I don't think this array need to be @State, maybe it can be static

Thanks for the suggestion! When I try that it says "Static property 'black' requires the types 'ShapeStyle' and 'Color' be equivalent" and "Static member 'black' cannot be used on protocol metatype 'ShapeStyle.Protocol' ".

I'm sorry, actually I'm wrong. You should keep your array as Color, they should be able to be used as ShapeStyle because Color's are ShapeStyle. Something else is wrong.

In this case, each of these sub-arrays is an array with both Colors and Ints. Swift needs to pick a concrete type to put into the array, so it has to find some set of protocols that these two types have in common. These two types don't have anything in common, so the compiler has to default to Any. The type of letterColors is Array<Array<Any>>, because the compiler now doesn't know that every even element of the array is a Color and every odd element is an Int.

Instead, consider making a struct that wraps the color and the number of times it's been clicked, and use that inside the array instead. Using multiple different types in an array is almost always a bad idea.

3 Likes