How do I randomly change the color of a circle?

Viewed 98

I'm beginning to try out SwiftUI. I want the Circle is randomly changing the color from red or green.

struct ContentView: View {
    @State var colorCircle = [".red", ".green"]

    var body: some View {
        ZStack {
            Circle()
                .fill(Color.colorCircle.randomElement())
                .frame(width: 100,
                       height: 100)
                .position(x: 250,
                          y: 320)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
1 Answers

First make your colorCircle array to contain Colors and not Strings.

@State var colorCircle: [Color] = [.red, .green]

Also note you're trying to access colorCircle from inside the Color struct:

Color.colorCircle.randomElement()

As you declared colorCircle in the ContentView you can use it like:

self.colorCircle.randomElement()

or (shorter):

colorCircle.randomElement()

Then you can use randomElement:

struct ContentView: View {
    @State var colorCircle: [Color] = [.red, .green]

    var body: some View {
        ZStack {
            Circle()
                .fill(colorCircle.randomElement()!)
                .frame(width: 100,
                       height: 100)
                .position(x: 250,
                          y: 320)
        }
    }
}

Note that randomElement() returns an optional so you can force-unwrap it (!) if you're sure your array is not empty.

However, as a good practice, I recommend not to use ! and provide default values if possible:

.fill(colorCircle.randomElement() ?? .red)
Related