Sharukh Sharukh - 7 months ago 745
Swift Question

Binary operator '..<' cannot be applied to operands of type 'Int' and 'CGFloat'

I'm trying to create a for loop but can't seem to understand how to get rid of this error

My code:

for i:CGFloat in 0 ..< 2 + self.frame.size.width / (movingGroundTexture.size().width) {
let sprite = SKSpriteNode(texture: movingGroundTexture)
sprite.zPosition = 0
sprite.anchorPoint = CGPointMake(0, 0)
sprite.position = CGPointMake(i * sprite.size.width, 0)

The error is on
line on


You cannot use the range operator with floating point types.

You either want to convert your 2 + self.frame.size.width / movingGroundTexture.size().width to an Int:

for i in 0 ..< Int(2 + self.frame.size.width / movingGroundTexture.size().width) { 
    // i is an Int      

Or you want to use stride:

// specify whatever value you want for the stride length – if it's just 1 you should probably just use a range with ints
for i in CGFloat(0).stride(to: 2 + self.frame.size.width / movingGroundTexture.size().width, by: 1) { 
    // i is a CGFloat   

Depends on whether you need floating point precision or not (as it appears you just want to increment the value by 1 at each iteration, I suspect you don't)