简体   繁体   中英

Adding variables to a static array in swift

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()
    }
}

You can use the static array without @state keyword

    static var arrS = [String]()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM