我正在尝试创建一个for循环,但似乎无法理解如何摆脱此错误
我的代码:
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) }
错误for在线上self.frame.size.width和(movingGroundTexture.aize().width)
for
self.frame.size.width
(movingGroundTexture.aize().width)
您不能使用浮点类型创建一个CountableRange(或CountableClosedRange)。
CountableRange
CountableClosedRange
您要么要将其转换2 + self.frame.size.width / movingGroundTexture.size().width为Int:
2 + self.frame.size.width / movingGroundTexture.size().width
Int
for i in 0 ..< Int(2 + self.frame.size.width / movingGroundTexture.size().width) { // i is an Int }
或者您想使用stride(Swift 2语法):
stride
for i in CGFloat(0).stride(to: 2 + self.frame.size.width / movingGroundTexture.size().width, by: 1) { // i is a CGFloat }
Swift 3语法:
for i in stride(from: 0, to: 2 + self.frame.size.width / movingGroundTexture.size().width, by: 1) { // i is a CGFloat }
取决于是否需要浮点精度。请注意,如果您的上限是一个非整数值,则该stride版本将比范围运算符版本多迭代一次,这是因为Int(...)它将忽略小数部分。
Int(...)