问题描述
我在这里有一个非常奇怪的错误,我已经搜索了所有内容,并尝试了所有建议.没有工作.
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迅捷!为什么不?我一直乘以Ints
.这两个 ARE 两个Ints
. globals.defaults
只是UserDefaults.standard
的一个实例.我每次都尝试使用相同的错误进行以下操作.
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...
所有这些尝试"似乎都是在浪费时间,因为我知道这两个事实都是Ints
...而且我是正确的.请指教.谢谢!
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!
推荐答案
该错误具有误导性.问题实际上是试图将Int
值分配给CGFloat
变量.
The error is misleading. The problem is actually the attempt to assign an Int
value to a CGFloat
variable.
这将起作用:
scrollView.contentSize.height = CGFloat(325 * globals.defaults.integer(forKey: "numCards"))
产生误导性错误的原因(由于下面的注释中的Daniel Hall)是由于编译器选择了*
函数,该函数由于需要返回值而返回了CGFloat
.该功能需要两个CGFloat
参数.由于提供的两个参数是Int
而不是CGFloat
,因此编译器提供了误导性错误:
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:
这篇关于快捷运算符"*"在两个Int上引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!