0

I currently have a List where it alternates the date (//Climb date group) and then details (//Climb details row) from core data every row.

I only want to show the date row though if it is different from the row above.

List{
            ForEach(climbs, id: \.self){ thisClimb in
                let gradeText = (thisClimb as? Climb)?.grade
                let attemptsText = (thisClimb as? Climb)?.attempts
                let passfailText = (thisClimb as? Climb)?.passfail ?? "climb string err"
                let newclimbdateText = (thisClimb as? Climb)?.climbdate
                
                
                //Climb date group
                if(oldclimbdateText != newclimbdateText){
                    HStack{
                        Spacer()
                        Text(newclimbdateText!.addingTimeInterval(600), style: .date).fontWeight(.medium)
                        Spacer()
                    }
                }
                
                //Climb details row
                HStack{
                    Text(gradesV[Int(gradeText!)])
                    Spacer()
                    Text("\(attemptsText!) attempts")
                    Spacer()
                    Text(passfailText)
                }

            }.onDelete(perform: deleteClimb)
        }

The code above shows this:

iPhone screenshot

So to not show the dates that are the same (see multiple Oct-18 above), what I tried to do is set a variable outside of the loop called @State private var oldclimbdateText and then within the if statement under "//Climb date group" I tried to set `oldclimbdateText = newclimbdateText``. That way on the next loop they do match does not enter the if statement.

However, when I try that I get the error Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

I'm just doing this for fun to learn. Using Xcode 12 and Swift5.

  1. Why do I get this error, and 2) is there a better way to get rid of these duplicate date rows?
Gil
  • 161
  • 1
  • 14
  • It's definitely not going to work with a single `@State` variable. `ForEach` view is not the same as a for each loop. The best approach is to prep the data beforehand, so that the view has a very easy job to decide whether to display something or not – New Dev Oct 19 '20 at 04:43
  • Does this answer your question? [How to dynamically create sections in a SwiftUI List/ForEach and avoid "Unable to infer complex closure return type"](https://stackoverflow.com/questions/58574847/how-to-dynamically-create-sections-in-a-swiftui-list-foreach-and-avoid-unable-t) – Andrew Oct 19 '20 at 05:04
  • You're kinda using an anti-pattern here, this kind of data manipulation should not be done at the View (UI) level, instead recommending to filter out the data before sending it to the view. – Cristik Oct 19 '20 at 06:12

0 Answers0