1

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!

1 Answer 1

1

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.

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

4 Comments

When I made the change I get an Unable to infer complex closure return type; add explicit type to disambiguate, then another message Use of unresolved operator '..'; did you mean '...'?
Figured it out. changed to 0...(testData.count - 1) and it works. Is there a "better" way to go about cycling through an array and building views like this?
Make sure to include the < after ..
It depends on what you're trying to achieve. Another solution would be to make People conform to Identifiable. Then you can iterate over the items in the array and not the count, so you wouldn't need to worry about indexes.

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.