0

I have a static array in swift and I want to append variables to it. It works fine, if I have just a normal array that is not static, but if I change the variable to static, it doesn't work. Is there a way to append Items to a static array in Swift?

Here is an example Code: This example works fine, until you comment the 3 non Static Versions and uncomment the 3 Static Versions, then it doesn't work.

import SwiftUI

struct ContentView: View {
    
    //Static Version:
    //@State static var arr = [String]()
    
    //non static Version:
    @State var arr = [String]()
    
    
    func appendToArray() {
        //Static Version:
        //ContentView.arr.append("Test")
    
        //non static Version:
        arr.append("Test")
    }
    func testArray() {
        //Static Version:
        //print(ContentView.arr[0])

        //non static Version:
        print(arr[0])
    }
    
    var body: some View {
        VStack {
                    
            Spacer()
            Button(action: {
                appendToArray()
            }){
                Text("Add something!!")
            }
            Spacer()
            Button(action: {
                testArray()
            }) {
                Text("Show Array Data")
            }
            Spacer()
                        
        }
    }
}

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

2
  • 6
    Please show a minimal reproducible example. Commented Dec 27, 2020 at 0:58
  • 1
    Updated it! Sorry for not asking a question without example. Commented Dec 27, 2020 at 1:11

1 Answer 1

1

You can use the static array without @state keyword

    static var arrS = [String]()
Sign up to request clarification or add additional context in comments.

Comments

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.