Hi there,
I have build WeSplit (first app tutorial in 100 days of SwiftUI), as well as a couple of other apps in the series. It's fair to say I'm a complete beginner. I thought it'd be a good idea to try and build WeSplit again, from scratch, to see how much I could remember. However I encountered a crash, which I just can't seem to get my head around. I've managed to work out basically which bit is causing the crash but I don't quite understand why.
Anyway here's my little bit of code to represent the problem.
struct ContentView: View {
@State private var tipSelection = 2
let tipsArray = [5, 10, 15, 20, 0]
var body: some View {
NavigationView {
Form {
Picker("Tip Selection", selection: $tipSelection) {
ForEach(tipsArray, id: \.self) {
Text("\($0)%")
}
}
.pickerStyle(SegmentedPickerStyle())
Text("\(tipsArray[tipSelection])")
}
.navigationBarTitle("WeSplit")
}
}
}
The code compiles fine but whenever I attempt to select a different picker value in the simulator the code crashes. It says Fatal error: Index out of range. It's weird because when you comment out the line below, the picker works as intended and you can freely select different percentages. Hopefully that all makes sense!
Text("\(tipsArray[tipSelection])")
I was hoping that someone might be able to show me how I could correct my code and, more importantly, explain why my code crashes and I get the error? Many thanks for your help with my very basic question!