xcode 二元运算符“..<”不能应用于“Int”和“CGFloat”类型的操作数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37401102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:50:02  来源:igfitidea点击:

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

xcodeswiftsprite-kit

提问by Sharukh

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

我正在尝试创建一个 for 循环,但似乎无法理解如何摆脱这个错误

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 forline on self.frame.size.widthand (movingGroundTexture.aize().width)

错误for在线self.frame.size.width并且(movingGroundTexture.aize().width)

回答by Hamish

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

您不能使用浮点类型创建CountableRange(或CountableClosedRange)。

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

您要么想将您的转换2 + self.frame.size.width / movingGroundTexture.size().widthInt

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):

或者你想使用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 syntax:

Swift 3 语法:

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 strideversion will iterate one more time than the range operator version, due to the fact that Int(...)will ignore the fractional component.

取决于您是否需要浮点精度。请注意,如果您的上限是非整数值,则该stride版本将比范围运算符版本多迭代一次,因为Int(...)会忽略小数部分。

回答by Code Different

You have to convert the right side of the range to an integer type, like Intor UInt:

您必须将范围的右侧转换为整数类型,例如Intor UInt

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