Reputation: 568
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()
}
}
Upvotes: 0
Views: 594
Reputation: 1984
You can use the static array without @state keyword
static var arrS = [String]()
Upvotes: 1