skip to Main Content

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!

2

Answers


  1. 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.

    Login or Signup to reply.
  2. For future readers, if you’re using this in a scroll view or non list context that doesn’t support an array being injected:

    ForEach(logs.indices, id:.self) { index in
        Text(logs[index])
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search