2
votes

I've got some simple code that creates an array (newFactoid) by calling a function (createSampleData) which it then holds as a State. A view displays record 1 of the array. So far so good. However, I'm trying to insert a button into the view which calls a simple function (refreshFactoid) which shuffles the array, in theory causing the view to refresh. The problem is I'm getting the above error when I insert the button/function. If I remove the button the error disappears. Any pointers/help appreciated.

import SwiftUI

struct ContentView : View {

    @State private var newFactoid = createSampleData()

    var body: some View {

        VStack {

        // Display Category
            Text(newFactoid[1].category).fontWeight(.thin)
            .font(.title)

        // Display Image
        Image("Factoid Image \(newFactoid[1].ref)")
            .resizable()
            .scaledToFit()
            .cornerRadius(15)
            .shadow(color: .gray, radius: 5, x:5, y:5)
            .padding(25)

        // Display Factoid
        Text("A: \(newFactoid[1].fact)")
            .padding(25)
            .multilineTextAlignment(.center)
            .background(Color.white)
            .cornerRadius(15)
            .shadow(color: .gray, radius: 5, x:5, y:5)
            .padding(25)

        // Display Odds
        Text("B: \(newFactoid[1].odds)").fontWeight(.ultraLight)
            .font(.title)
            .padding()
            .frame(width: 150, height: 150)
            .clipShape(Circle())
            .multilineTextAlignment(.center)
            .overlay(Circle().stroke(Color.white, lineWidth: 2))
            .shadow(color: .gray, radius: 5, x: 5, y: 5)

        // Refresh Button
        Button (action: {refreshFactoid()}) {
            Text("Press To Refresh Data")
        }

       // Refresh Function
        func refreshFactoid() {
             newFactoid.shuffle()
             }

        } // End of VStack Closure

    }
}

struct TextUIView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        }
    }
2

2 Answers

1
votes

just remove

   // Refresh Function
    func refreshFactoid() {
         newFactoid.shuffle()
         }

    } // End of VStack Closure

from the body

1
votes

The func cannot be declared in the VStack.

Either trigger the shuffle in the action block of the Button:

Button(action: { self.newFactoid.shuffle() }) {
    Text("Press To Refresh Data")
}

or declare the function in the View struct:

struct ContentView: View {

    @State private var newFactoid = createSampleData()

    var body: some View {

        VStack {
            // ...

            // Refresh Button
            Button(action: { self.refreshFactoid() }) {
                Text("Press To Refresh Data")
            }

        } // End of VStack Closure

    }

    // Refresh Function
    func refreshFactoid() {
        newFactoid.shuffle()
    }

}