James Ellsworth
James Ellsworth

Reputation: 27

Incrementing a variable in a ForEach loop (SwiftUI)

I am trying to write code that creates a sunburst chart by drawing a series of arcs based on percentages in an array. However, whenever I try and edit a variable inside the ForEach loop, swift gives the following error: "Generic parameter 'S' could not be inferred" on the line with .stroke. Is there something I am doing wrong with my code?

struct pen: View {
let percentages = [19.9, 15.8, 13.7, 9.9, 9.9, 9.4, 7.4, 5.4, 3.1, 2.9, 2.6,]
let changes = [100.5, 101.2, 97.6, 101.8, 98, 98.4, 104.5, 102.9, 99.6, 104.5, 95.4]

@State var cOpacity = 0.0
@State var cColor = 0.0
@State var cAngle = 0.0
@State var nAngle = 0.0
@State var i = 0
var body: some View {
    ZStack {
        ForEach((1...10).reversed(), id: \.self) {listItem in
            VStack {
                cAngle = nAngle
                nAngle = cAngle + percentages[listItem - 1]
                Arc(startAngle: .degrees(0.0), endAngle: .degrees(50.0), clockwise: false)
                                .stroke(Color.green, lineWidth: CGFloat(15)) //Generic parameter 'S' could not be inferred
                    .opacity(100.0)
                    .frame(width: CGFloat(300), height: CGFloat(300))
                Text(String(listItem))
            }
        }
    }
  }
}

Upvotes: 2

Views: 1680

Answers (1)

RPatel99
RPatel99

Reputation: 8096

First off, code in the ForEach is in a closure so you need to explicitly do self.. Also, your VStack can't infer a return type since there is other code in there, so I recommend making a function that does it all. I don't know for sure if this will fix everything, but try changing your code to

struct pen: View {
let percentages = [19.9, 15.8, 13.7, 9.9, 9.9, 9.4, 7.4, 5.4, 3.1, 2.9, 2.6,]
let changes = [100.5, 101.2, 97.6, 101.8, 98, 98.4, 104.5, 102.9, 99.6, 104.5, 95.4]

@State var cOpacity = 0.0
@State var cColor = 0.0
@State var cAngle = 0.0
@State var nAngle = 0.0
@State var i = 0
var body: some View {
    ZStack {
        ForEach((1...10).reversed(), id: \.self) {listItem in
            self.render(listItem: listItem)
        }
    }

    func render(listItem: Int) -> some View {
        self.cAngle = self.nAngle
        self.nAngle = self.cAngle + self.percentages[listItem - 1]
        return VStack {
            Arc(startAngle: .degrees(0.0), endAngle: .degrees(50.0), clockwise: false)
                .stroke(Color.green, lineWidth: CGFloat(15))
                .opacity(100.0)
                .frame(width: CGFloat(300), height: CGFloat(300))
            Text(String(listItem))
        }
    }
  }
}

Upvotes: 1

Related Questions