Search code examples
xcodeswiftuixcode12

refreshing RandomElement() in SwiftUI


I have a list of Colors that I want to refresh using a button. this is what I have right now.

var body: some View {
        
        let happy = ["red","blue","purple","green"]
        let randomHappy = happy.randomElement()!
        
        ZStack {
            
            Rectangle()
                .foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
                .ignoresSafeArea()
            
            VStack{
            
            Text(randomHappy)
            
            Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/, label: {
                Text("Button")
                    .foregroundColor(.black)
            })
            }
                
        }
        
    }
}


I considered refreshing the whole page, but I think that might be too excessive just to refresh the result of a random element. does anyone have an idea on how to fix this?


Solution

  • You can use @State to store a random element from the array.

    struct ContentView: View {
        static let happy = ["red","blue","purple","green"]
    
        @State var randomHappy = Self.happy.randomElement()!
        
        var body: some View {
            
            ZStack {
                
                Rectangle()
                    .foregroundColor(.blue)
                    .ignoresSafeArea()
                
                VStack{
                    
                    Text(randomHappy)
                    
                    Button(action: {
                        randomHappy = Self.happy.randomElement()!
                    }) {
                        Text("Button")
                            .foregroundColor(.black)
                    }
                }
                
            }
        }
    }
    

    Under almost all normal circumstances, I wouldn't recommend force unwrapping with !, but in this situation, you can guarantee that you'll always get an element back, so it seems reasonable.