Stephen Flournoy
Stephen Flournoy

Reputation: 107

Program crashing using ForEach loop in SwiftUI

I'm a beginner in Swift and SwiftUI.

I setup my sample data model in a file PeopleModel.swift, here is that code:

import Foundation

struct People {

    var name : String

    static let demoPeople = [
        People(name:"Stephen"),
        People(name:"John"),
        People(name:"Jack")]

}

To use the data model I thought I would try to iterate through the list with this code:

import SwiftUI

struct ListPersonView: View {

    let testData = People.demoPeople

    var body: some View {

        VStack {
            ForEach((0...testData.count), id: \.self) {result in
                Text( self.testData[result].name)
            }

            Text("Ready or not, here I come!")

        }

    }//View

}//struct

struct ListPersonView_Previews: PreviewProvider {
    static var previews: some View {
        ListPersonView()
    }
}

When I run the previewer, the program crashes. I must me missing something easy, but would appreciate an idea where I am going wrong. Thank you!

Upvotes: 1

Views: 948

Answers (1)

Vlad
Vlad

Reputation: 1041

The range in your ForEach loop is open, so you will get an out of bounds exception when you try access self.testData[result].name when result is equal to the length of testData.

Changing your range to 0..<testData.count should fix your problem.

Upvotes: 1

Related Questions