ios - swift 3 错误 : "Binary operator ' /' cannot be applied to two ' int' operands"

标签 ios swift swift3

<分区>

我知道有一个标题相同的问题,但我认为这是一个不同的问题,因为我无法用提供的解决方案解决它。相关问题是:Binary operator '/' cannot be applied to two (Int) operands .我也看过了应该是原始问题。

但我只是在尝试使用 UIColor 函数中的变量时才遇到此错误:

工作

UIColor(red: 74/255, green: 24/255, blue: 141/255, alpha: 1)

不起作用

var colorRGB = 74
UIColor(red: colorRGB/255, green: 24/255, blue: 141/255, alpha: 1)

所以我无法理解为什么会发生错误。它抛出以下错误:

Binary operator '/' cannot be applied to two 'int' operands

我认为它会是相同的,因为在两种情况下它的值都相同,但我却收到了那个错误。我认为在第一个示例中还有两个 int 值,它不会引发该错误。

如何在我的函数中使用变量?

提前致谢!

最佳答案

UIColor 构造函数有四个 CGFloat 参数。

UIColor(red: 74/255, green: 24/255, blue: 141/255, alpha: 1)

编译因为 CGFloat 符合 ExpressibleByIntegerLiteral 协议(protocol)。从上下文中编译器试图使 74/255 一个CGFloat,并将所有数字解释为CGFloat 文字,/ 作为 CGFloat 除法运算符。

这不适用于

var colorRGB = 74
UIColor(red: colorRGB/255, green: 24/255, blue: 141/255, alpha: 1)

74 文字没有上下文,所以它被采用 默认情况下作为 Int。但是没有 合适的除法运算符使 colorRGB/255 成为 CGFloat

您必须使用正确的类型显式定义变量:

var colorRGB: CGFloat = 74
UIColor(red: colorRGB/255, green: 24/255, blue: 141/255, alpha: 1)

备注:这也会编译:

var colorRGB = 74
UIColor(red: CGFloat(colorRGB/255), green: 24/255, blue: 141/255, alpha: 1)

但是 colorRGB/255 变成了 整数除法 并计算 归零,比较Strange Swift numbers type casting .

关于ios - swift 3 错误 : "Binary operator ' /' cannot be applied to two ' int' operands",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40870334/

相关文章:

javascript - iOS Swift 如何将 JSON 字符串和数组或字典从 UIWebView 传递给 Javascript?

ios - 如何更改用户安装的 webview 的 url? Xcode

ios - Storyboard输出与模拟不匹配

iPhone - 获取 UIView 在整个 UIWindow 中的位置

ios - UIKIT_DEFINE_AS_PROPERTIES 在哪里定义的?

iphone - 如何通过 App Store 更新使用预填充的核心数据数据库仅更新几个表

ios - Swift 3 中的通知中心崩溃

ios - 禁用 uicollectionview 水平滚动的外部平移手势

ios - 按下后退按钮时,UITableView 中的数据会重复

google-maps - swift 3 : How to remove the tracked polyline in Google map