Home > database >  Access variable inside a function SwiftUI
Access variable inside a function SwiftUI

Time:09-24

I have been trying to access a variable from inside a function and am struggling to find a way to do so.

Below is an idea of what I am trying to achieve. For example, when the function testFunc is run, it will shuffle an array. I want to get the result of that array back into the body of the struct, but am struggling to do so.

Some ideas I have tried include binding variables but it seems gets confusing as I am relatively inexperienced. Is there a method to achieve this or would using the binding variables be the best way to go?

Any help would be greatly appreciated. Thank you!

struct ContentView: View {

var body: some View {

testFunc()

} 

func testFunc() {

var tester = ["a", "b", "c"].shuffled

}
}

CodePudding user response:

A body have to include views, so possible variant (while I'm not really sure clearly understood your goal) could be

func testFunc() -> some View {
    let tester = ["a", "b", "c"].shuffled()
    return VStack {
        ForEach(tester, id: \.self) { Text($0) }
    }
}

CodePudding user response:

Asperi just answered your question! but I do not think you need a function, you need to just access the array for shuffle, like this code:

struct ContentView: View {
    
    @State private var array: [String] = ["a", "b", "c", "d"]
    
    var body: some View {
        
        ForEach(array, id:\.self) { item in
            
            Text(item)
            
        }
        
        Button("shuffle") {
            array.shuffle()
        }
        .padding()
        
    }
    
}
  • Related