UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Fatal error: Index out of range?

Forums > SwiftUI

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) {




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!


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!


Okay, so as is usually the case, having not been able to figure it out for a good few hours, I've now got it working! This was by replacing:




Now the text box displays the percentage number like I intented. But my confusion still remains. Why would the tip selection not just be from 0-4 (since it's default value is 2), rather than showing the actual values in the tipsArray.


You are thinking of the tipSelection as though it were an index, but it is the actual value of the array item added to the picker within your ForEach loop. It displays a 2 because you set it to 2 by default.


Okay thanks a lot for helping clear that up. Really appreciate it!


Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.