Chris
Chris

Reputation: 589

Replacement for C-style loop in Swift 2.2 CGFloat

I have tried this with CGFloat and i am getting the following error: Can not invoke stride with an argument list of type '(CGFloat by: CGFloat)'

for var min:CGFloat = 0.0; min<=45.0; min = min+value {

print("\(min)")
}

to:

for min:CGFloat in 0.stride(CGFloat(55.0), by: min+value) {

   print("\(min)")
}

Upvotes: 1

Views: 691

Answers (2)

neo
neo

Reputation: 1298

Below is the latest overload for stride. You can use cast the number to CGFloat for the stride.

for min in (0 as CGFloat).stride(to: 55, by: value) {
    print("\(min)")
}

However, stride returns a Striable when the for-loop begin. The by value does not update with the iteration of for-loop. A while-loop would be better for this case,

var min : CGFloat = 0

while (min < 55) {
    print("\(min)")
    min += value
}

Upvotes: 1

user3441734
user3441734

Reputation: 17544

import Foundation

let fromValue = CGFloat(0.0)
let toValue = CGFloat(10.0)
let distance = CGFloat(3.3)


// stride in interval from 0.0 ..< 10.0, with distance 3.3

let sequence = fromValue.stride(to: toValue, by: distance)
print(sequence.dynamicType)
/*
 StrideTo<CGFloat>
 */

// StrideTo conforms to SequenceType protocol, so we can use for-in
for element in sequence {
    print("\(element)")
}
/*
 0.0
 3.3
 6.3
 9.9
*/

Upvotes: 0

Related Questions