从字符串更改为双精度的 Swift 错误(为什么字符串类型编号变为 nil?

Swift error with change from string to double (why String type number becomes nil?)

提问人:Hoyeon Lee 提问时间:11/8/2022 最后编辑:Hoyeon Lee 更新时间:11/9/2022 访问量:273

问:

我正在尝试制作自己的玩具项目来研究 Swift。 但是我在将字符串转换为双精度时遇到了问题。

请先参考以下代码。

//MARK: - ExchangeManagerDelegate
extension ViewController: ExchangeManagerDelegate {
    func didUpdateCurrency(price: String) {
        DispatchQueue.main.async {
            print(price)  // [result] 1392.43
            let priceDouble = Double(price) ?? 0
            print(priceDouble)  // [result] 0.0
            let inputPrice = Double(self.currency1Price.text!)
            print(inputPrice!)  // [result] 10.0
            let result = Double(price)! * inputPrice!
            print(result)  // [result] Fatal error: Unexpectedly found nil while unwrapping an Optional value
            self.currency2Price.text = String(format: "%.2f", result)
        }
    }
    
    func didFailWithError(error: Error) {
        print(error)
    }
    
}

首先,请注意,这是来自 JSON 解析的字符串,我检查了它按预期打印出 1392.43priceprice

当我尝试将 String() 转换为 Double() 时,似乎被指定为 nil,因此它在控制台中打印出 0pricepriceDoublepriceDouble

因此,我尝试了 NSString 的不同方式,但它打印出了 1.0

//MARK: - ExchangeManagerDelegate
extension ViewController: ExchangeManagerDelegate {
    func didUpdateCurrency(price: String) {
        DispatchQueue.main.async {
            print(price)  // [result] 1392.43
            let priceDouble: Double = (price as NSString).doubleValue
            print(priceDouble)  // [result] 1.0
            let inputPrice = Double(self.currency1Price.text!)
            print(inputPrice!)  // [result] 10.0
            let result = Double(price)! * inputPrice!
            print(result)  // [result] Fatal error: Unexpectedly found nil while unwrapping an Optional value
            self.currency2Price.text = String(format: "%.2f", result)
        }
    }
    
    func didFailWithError(error: Error) {
        print(error)
    }
    
}

在这里,我想要 1392.43,最后有 13924.30 请让我知道为什么会出现此问题以及如何更改我的代码以使其正常工作。priceDoubleresult

swift 字符串 null double 选项类型

评论

0赞 HangarRash 11/8/2022
更改为 .结果是什么?对于字符串,它应该是:。如果失败,您的结果很可能会有所不同。print(price)print(Array(price.utf8))1392.43[49, 51, 57, 50, 46, 52, 51]Double(price)
0赞 Larme 11/8/2022
NSString.doubleValue是更允许的。您可以比较 & 、 其中 is 、 等的值。因此,如前所述,使用 .您还可以使用 a 来读取该值。(priceStr as NSString).doubleValueDouble(priceStr)priceStr" 1392.43"" 1 392.43""1392.43"print(Array(price.utf8))NumberFormatter
0赞 Hoyeon Lee 11/9/2022
非常感谢你,@HangarRash!我按照你的建议尝试,结果是 [49, 44, 51, 57, 50, 46, 52, 51]。在这里,我发现实际上包括逗号,您的评论在解决我的问题中起着决定性的作用!所以,我终于解决了我的问题。print(Array(price.utf8))pricelet priceWithoutComma = price.components(seperatedBy: [","]).joined()
0赞 Larme 11/9/2022
小心使用逗号。在某些语言中,它可以用来分隔千位,而其他语言可以用来分隔小数点......

答:

0赞 flanker 11/8/2022 #1

Double可以使用任何(或技术上的任何)进行初始化。如果该字符串是数字的有效表示(在任何基数中),它将返回相应值的 Double。字符串初始值设定项是可失败的,如果无法将字符串转换为 Double,则将返回。(这可能是在陈述您已经知道的内容,但为了以防万一而添加。StringStringProtocolnil

从表面上看,您应该能够转换字符串,但是转换失败,并且 nil 合并提供了默认值 。删除 nil 合并运算符应提供值 ,并且将是一个很好的检查。0.0nil

我的猜测是来自你的json的字符串有不可见的字符或空格

评论

0赞 Hoyeon Lee 11/9/2022
我终于解决了我的问题。原因是分配为“1,392.43”(包括逗号),而不是“1392.43”。当我尝试时,只有没有逗号的数字被打印成 1392.43,这样我就无法识别变量中的逗号。所以,这是我的解决方案,感谢您富有成效的评论。priceprint(price)let priceWithoutComma = price.components(seperatedBy: [","]).joined()
0赞 flanker 11/10/2022
很高兴你解决了它,但我希望你能控制后端,因为在某些语言环境中,使用逗号而不是句点来表示小数。