Swift operator “*” throwing error on two Ints

你。 提交于 2019-12-18 05:44:42

问题


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

Binary operator '*' cannot be applied to two 'Int' operands

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!


回答1:


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:

Binary operator '*' cannot be applied to two 'Int' operands

It would be nice if the error was more like:

Binary operator '*' cannot be applied to two 'Int' operands. Expecting two 'CGFloat' operands.



来源:https://stackoverflow.com/questions/40557214/swift-operator-throwing-error-on-two-ints

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!