0

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

}
}

1 Answer 1

1

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()
        
    }
    
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi! Thank you for the reply. I have tried that method before but for some reason, it comes up with a caution message saying the result of call to shuffled() is unused. Any ideas why that might be?
I have an idea! As I can see in your question, you are new to SwiftUI and you are thinking that you can run a Void in body of a View, which is wrong as Asperi mentioned! You are making that line of code but you are not process it to get run, see my code! it works perfectly because I am shuffling in action of a button! for sure your issue is not function, you need to study about SwiftUI in general.
Wow, it works perfectly! That is exactly what I was looking for thank you so much for all your help. I am slowly trying to learn but it's a lot to take in but I think I understand what you were saying. Thank you again!
You are welcome, happy to help you always if I can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.