二元运算符'..<'不能应用于“Int"和“CGFloat"类型的操作数 [英] 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)
addChild(sprite)
}
The error is on for
line on self.frame.size.width
and (movingGroundTexture.aize().width)
You cannot create a CountableRange
(or CountableClosedRange
) 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
(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-integral value, the stride
version will iterate one more time than the range operator version, due to the fact that Int(...)
will ignore the fractional component.
这篇关于二元运算符'..<'不能应用于“Int"和“CGFloat"类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!