4

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 ?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, this is kinda difficult to pick up, very different from other languages I've used in the past.
Swift is the language. SwiftUI is the user interface code. You can use Swift without SwiftUI by using UIKit instead (for example). That is how Swift was used to build apps for the first 5 years.

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.