C-Style for statement has been removed in swift 3

hi,

I update my xcode(xcode 7.3.1 to xcode 8.3.3), the i have been experienced an error "c-style for statement has been removed in swift3". How to convert the below

code in to swift3.1.


fileprivate func drawXGrid() {

x.grid.color.setStroke()

let path = UIBezierPath()

var x1: CGFloat

let y1: CGFloat = self.bounds.height - y.axis.inset

let y2: CGFloat = y.axis.inset

let (start, stop, step) = self.x.ticks

for var i: CGFloat = start; i <= stop; i += step { //c-style for statement has been removed in swift3

x1 = self.x.scale(i) + x.axis.inset

path.move(to: CGPoint(x: x1, y: y1))

path.addLine(to: CGPoint(x: x1, y: y2))

}

path.stroke()

}





fileprivate func drawYLabels() {

var yValue: CGFloat

let (start, stop, step) = self.y.ticks

for var i: CGFloat = start; i <= stop; i += step { //c-style for statement has been removed in swift3

yValue = self.bounds.height - self.y.scale(i) - (y.axis.inset * 1.5)

let label = UILabel(frame: CGRect(x: 0, y: yValue, width: y.axis.inset, height: y.axis.inset))

label.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption2) //c-style for statement has been removed in swift

label.textAlignment = .center

label.text = String(Int(round(i)))

self.addSubview(label)

}

}





How to convert the above for loop into swift 3.1. what shall i do to remove the error message.

As far as I can tell, you have to use a while-loop. The for-loop has been relegated to iterate over collections and containers (note that, in the example in the Swift Language Referece, in the construct "for i in 1...5", the 1...5 is an implicit collection of integers 1 through 5). You have to write something like:


var i : CGFloat = start

while i != stop {

... processing goes here ...

i += step

}


Jonathan

Should take care ; due to the way comparison is done with floats, the stop condition may never occur and you'll get an infinite loop.


Should test with a "< "condition;


var i : CGFloat = start
while i < stop  {
     ... processing goes here ...
     i += step
}


And you should check before that start <= stop, otherwise you'll get an infinite loop as well


But you have something closer to c-style original :


for i in stride(from: start, through: stop, by: step) {

}


Here no need to test start < stop ; it works also with negative step.

If I make it as close to c-style as possible. I can convert the code as the followings: for var i: CGFloat = start; i <= stop; i += step { //c-style for statement has been removed in swift3 x1 = self.x.scale(i) + x.axis.inset path.move(to: CGPoint(x: x1, y: y1)) path.addLine(to: CGPoint(x: x1, y: y2)) }

-> in Swift5.5 as of Oct 23, 2021. for i in sequence(first:start, next:{ (($0-step)<=stop) ? $0+step:nil }) { x1 = self.x.scale(i) + x.axis.inset path.move(to: CGPoint(x: x1, y: y1)) path.addLine(to: CGPoint(x: x1, y: y2)) }

I hope this helps.

C-Style for statement has been removed in swift 3
 
 
Q