Home > front end >  Can I create a list element for each array value in SwiftUI
Can I create a list element for each array value in SwiftUI

Time:08-10

I'm am working on an app that tracks reading hours, and I am making a page that shows you all your logs with how much time you logged, and the date. I want to do this in a SwiftUI List format. My problem is I have an array of the logs, but I need to somehow loop through that array, and create a Text element in the list for every array value. Here is my code:

List{
   for i in log {
     Text(log[i])
   }
}

This is inside a NavigationLink by the way, I don't think that would be the problem though. It is also surrounded by the defualy ContentView.swift stuff and is inside the "var body: some View" function like it should be. The log array is inside ContentView but outside the "var body: some view". And when I run this I get an error that says, "Closure containing control flow statement cannot be used with result builder 'ViewBuilder'"

As you can probably tell I am very new to swift and IOS design. Any pointers would be hugely appreciated. Thanks!

CodePudding user response:

List has it's own syntax for loopable content:

// Must have id:\.self so SwiftUI can tell each log apart from the others. 
// Make sure each log has something unique (i.e. a precise timestamp)
List(log, id: \.self) { i in
    Text(i)
}

I agree with Asperi, though. You should absolutely run through a SwiftUI Basics course so you can get used to SwiftUI's syntax.

  • Related