问题描述
我在这里遇到了一个非常奇怪的错误,我四处搜索并尝试了所有建议.没有工作.
scrollView.contentSize.height = 325 * globals.defaults.integer(forKey: "numCards")
二元运算符*"不能应用于两个Int"操作数
WTF 斯威夫特!为什么不?我一直乘着 Ints
.这些是两个Ints
.globals.defaults
只是 UserDefaults.standard
的一个实例.我每次都尝试了以下相同的错误.
325 * Int(globals.defaults.integer(forKey: "numCards")//NOPEInt(325) * Int(globals.defaults.integer(forKey: "numCards"))//NOPEif let h = globals.defaults.integer(forKey: "numCards"){325 * h//NOPE,和'条件绑定的初始化器必须具有可选类型,而不是Int'}让 h = globals.defaults.integer(forKey: "numCards") as!整数325 * h//NOPE,和'强制转换相同类型的 Int 没有影响'325 * 2//是的!但是没有狗屎...
所有这些尝试"似乎都是在浪费时间,因为我知道这两个都是Ints
...我是对的.请指教.谢谢!
该错误具有误导性.问题实际上是试图将 Int
值分配给 CGFloat
变量.
这会起作用:
scrollView.contentSize.height = CGFloat(325 * globals.defaults.integer(forKey: "numCards"))
误导性错误的原因(感谢 Daniel Hall 在下面的评论中)是由于编译器选择了返回 CGFloat
的 *
函数,因为返回需要的价值.这个相同的函数需要两个 CGFloat
参数.由于提供的两个参数是 Int
而不是 CGFloat
,编译器提供了误导性错误:
二元运算符*"不能应用于两个Int"操作数
如果错误更像:
二元运算符*"不能应用于两个Int"操作数.需要两个CGFloat"操作数.
I have a very odd error here and i've searched all around and i have tried all the suggestions. None work.
scrollView.contentSize.height = 325 * globals.defaults.integer(forKey: "numCards")
WTF Swift! Why not? I multiply Ints
all the time. These ARE two Ints
. globals.defaults
is just an instance of UserDefaults.standard
. I have tried the following with the same error each time.
325 * Int(globals.defaults.integer(forKey: "numCards") //NOPE
Int(325) * Int(globals.defaults.integer(forKey: "numCards")) //NOPE
if let h = globals.defaults.integer(forKey: "numCards"){
325 * h //NOPE, and 'Initializer for conditional binding must have optional type, not Int'
}
let h = globals.defaults.integer(forKey: "numCards") as! Int
325 * h //NOPE, and 'Forced cast of Int of same type as no affect'
325 * 2 //YES! But no shit...
All of those "attempts" seemed like a waste of time as i know for a fact both of these are Ints
...and i was correct. Please advise. Thanks!
The error is misleading. The problem is actually the attempt to assign an Int
value to a CGFloat
variable.
This will work:
scrollView.contentSize.height = CGFloat(325 * globals.defaults.integer(forKey: "numCards"))
The cause of the misleading error (thanks to Daniel Hall in the comments below) is due to the compiler choosing the *
function that returns a CGFloat
due to the return value needed. This same function expects two CGFloat
parameters. Since the two arguments being provided are Int
instead of CGFloat
, the compiler provides the misleading error:
It would be nice if the error was more like:
这篇关于Swift 运算符“*"在两个 Int 上抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!