二元运算符'..<'不能应用于“Int"和“CGFloat"类型的操作数 [英] Binary operator &#39;..&lt;&#39; cannot be applied to operands of type &#39;Int&#39; and &#39;CGFloat&#39;

查看:37
本文介绍了二元运算符'..<'不能应用于“Int"和“CGFloat"类型的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的代码:

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

错误位于 self.frame.size.width(movingGroundTexture.aize().width) 上的 for 行>

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

推荐答案

您不能创建 CountableRange(或CountableClosedRange) 与浮点类型.

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

您要么想将 2 + self.frame.size.width/movingGroundTexture.size().width 转换为 Int:

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      
}

或者你想使用 stride(Swift 2 语法):

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 语法:

Swift 3 syntax:

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

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

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆