我正在尝试创建一个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)
行
答案 0 :(得分:10)
您无法使用浮点类型创建CountableRange
(或CountableClosedRange
)。
您要么将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语法):
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(...)
将忽略小数组件。
答案 1 :(得分:5)
您必须将范围的右侧转换为整数类型,例如Int
或UInt
:
for i in 0 ..< Int(2 + self.frame.size.width / (movingGroundTexture.size().width)) {
...
}