jellyshoe
jellyshoe

Reputation: 551

Modify variable in SwiftUI

Let's say I have this code:

var n = 3
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

struct ContentView: View {
    var body: some View {
        Text(String(arr[n])
    }
}

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

I want to set arr[n] to let's say, 100. Where and how would I go about doing that? I can't put it right after the array declaration since its the top level, and I can't put it inside the ContentView struct.

I'm new to Swift so it would be really helpful if I could get an explanation.

Edit: Additionally if i have this code:

var n = 3


struct ContentView: View {
    @State var arr[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    var body: some View {
        Text(String(self.arr[n])
    }
}

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

where would I be able to put self.arr[n] = 0 ?

Upvotes: 4

Views: 4933

Answers (1)

vacawama
vacawama

Reputation: 154721

SwiftUI is a declarative interface. In order to run code, you need to capture some event, such as .onAppear or .onTapGesture:

var n = 3

struct ContentView: View {
    @State private var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    var body: some View {
        Text(String(arr[n])).onTapGesture {
            self.arr[n] = 100
        }
    }
}

When this first displays, the value of arr[3] is 4 and that is displayed in the middle of the screen.

When 4 is tapped, the closure following .onTapGesture runs and the arr[3] value gets updated to 100, and because arr is a @State variable, the View will redraw itself using the new value.

If arr were declared outside of ContentView like in your first example, then updating it would not cause ContentView to redraw.

Upvotes: 3

Related Questions