微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift操作符“*”在两个Ints上抛出错误

在这里一个非常奇怪的错误,我搜索了周围,我已经尝试了所有的建议.没有工作
scrollView.contentSize.height = 325 * globals.defaults.integer(forKey: "numCards")

Binary operator ‘*’ cannot be applied to two ‘Int’ operands

WTF Swift!为什么不?我一直乘以Ints.这些是两个Ints. globals.defaults只是UserDefaults.standard的一个实例.我每次尝试以下相同的错误.

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 …而且我是正确的.请指教.谢谢!

错误是误导性的.该问题实际上是试图将一个Int值分配给一个CGFloat变量.

这将工作:

scrollView.contentSize.height = CGFloat(325 * globals.defaults.integer(forKey: "numCards"))

导致误导性错误的原因(感谢Daniel Hall在下面的评论中)是由于编译器选择返回CGFloat的*函数,因为需要返回值.这个相同的功能需要两个CGFloat参数.由于提供的两个参数是Int而不是CGFloat,所以编译器提供了误导性的错误

Binary operator ‘*’ cannot be applied to two ‘Int’ operands

如果错误更像:

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

原文地址:https://www.jb51.cc/swift/318775.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐