无法将NSNumber桥接到Float Swift 3.3 [英] Unable to bridge NSNumber to Float Swift 3.3

查看:250
本文介绍了无法将NSNumber桥接到Float Swift 3.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新Xcode之后,我遇到了一个奇怪的问题.在我的应用程序中,当我从API获得响应时,我会手动解析它并将其映射到我的模型.在我的代码中,有很多地方都将JSON值强制转换为Float,并进行空合并,如下所示:

After an Xcode update I encountered a weird problem. In my application, when I get a response from an API, I parse it manually and map it to my model. There are a lot of places in my code where I cast a JSON value to Float with null coalescing like below:

randomVariable = jsonDict["jsonKey"] as? Float ?? 0

它过去可以正常工作,但是在更新后,它始终默认为0.为了确定原因,我尝试强制将其强制转换为Float,如下所示:

It used to work fine but after the update, it would always default to 0. In order to determine the cause, I tried force casting it to Float like below

randomVariable = jsonDict["jsonKey"] as! Float

这导致了以下错误

无法将NSNumber桥接到Float

Unable to bridge NSNumber to Float

在进一步调查中,我发现Xcode使用的是Swift 3.3(以前使用的是Swift 3.2).我在StackOverflow上发现的解决方案围绕着将其强制转换为NSNumber而不是Float.正如我上面提到的,我在应用程序中分布了相似的代码行.我想知道是否有解决此问题的方法.也许使用某种扩展名?

Upon further investigation, I found out that Xcode is using Swift 3.3 (previously, it was using Swift 3.2). The solutions I found on StackOverflow revolve around casting it to NSNumber instead of Float. As I mentioned above, I have similar lines of code spread across my app. I was wondering if there is a way to fix this issue. Maybe using an extension of some sort?

推荐答案

您已经发现,您可能需要先将其转换为NSNumber.

As you have found, you may need to cast it first to NSNumber.

类似这样的东西:

randomVariable = (jsonDict["jsonKey"] as? NSNumber)?.floatValue ?? 0

也许正则表达式替换将帮助您更新代码.

Maybe regex replacement would help you update your code.

模式:jsonDict\[([^\]]*)\] as\? Float

替换为:(jsonDict[$1] as? NSNumber)?.floatValue

这篇关于无法将NSNumber桥接到Float Swift 3.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆