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

I am trying to create a for loop but cannot figure out how to get rid of this error.

My code is:

 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) addChild(sprite) } 

The error is on the for line on self.frame.size.width and (movingGroundTexture.aize().width)

+5
source share
2 answers

You cannot create a CountableRange (or CountableClosedRange ) with floating point types.

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

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

Or do you want to use stride (Swift 2 syntax):

 for i in CGFloat(0).stride(to: 2 + self.frame.size.width / movingGroundTexture.size().width, by: 1) { // i is a CGFloat } 

Swift 3 Syntax:

 for i in stride(from: 0, 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. Note that if your upper bound is a non-integer value, the stride version will iterate again than the range operator version, because Int(...) will ignore the fractional component.

+10
source

You need to convert the right side of the range to an integer type, for example Int or UInt :

 for i in 0 ..< Int(2 + self.frame.size.width / (movingGroundTexture.size().width)) { ... } 
+5
source

All Articles