提问人:Hoyeon Lee 提问时间:11/8/2022 最后编辑:Hoyeon Lee 更新时间:11/9/2022 访问量:273
从字符串更改为双精度的 Swift 错误(为什么字符串类型编号变为 nil?
Swift error with change from string to double (why String type number becomes nil?)
问:
我正在尝试制作自己的玩具项目来研究 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.43。price
price
当我尝试将 String() 转换为 Double() 时,似乎被指定为 nil,因此它在控制台中打印出 0。price
priceDouble
priceDouble
因此,我尝试了 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。
请让我知道为什么会出现此问题以及如何更改我的代码以使其正常工作。priceDouble
result
答:
0赞
flanker
11/8/2022
#1
Double
可以使用任何(或技术上的任何)进行初始化。如果该字符串是数字的有效表示(在任何基数中),它将返回相应值的 Double。字符串初始值设定项是可失败的,如果无法将字符串转换为 Double,则将返回。(这可能是在陈述您已经知道的内容,但为了以防万一而添加。String
StringProtocol
nil
从表面上看,您应该能够转换字符串,但是转换失败,并且 nil 合并提供了默认值 。删除 nil 合并运算符应提供值 ,并且将是一个很好的检查。0.0
nil
我的猜测是来自你的json的字符串有不可见的字符或空格
评论
0赞
Hoyeon Lee
11/9/2022
我终于解决了我的问题。原因是分配为“1,392.43”(包括逗号),而不是“1392.43”。当我尝试时,只有没有逗号的数字被打印成 1392.43,这样我就无法识别变量中的逗号。所以,这是我的解决方案,感谢您富有成效的评论。price
print(price)
let priceWithoutComma = price.components(seperatedBy: [","]).joined()
0赞
flanker
11/10/2022
很高兴你解决了它,但我希望你能控制后端,因为在某些语言环境中,使用逗号而不是句点来表示小数。
评论
print(price)
print(Array(price.utf8))
1392.43
[49, 51, 57, 50, 46, 52, 51]
Double(price)
NSString.doubleValue
是更允许的。您可以比较 & 、 其中 is 、 等的值。因此,如前所述,使用 .您还可以使用 a 来读取该值。(priceStr as NSString).doubleValue
Double(priceStr)
priceStr
" 1392.43"
" 1 392.43"
"1392.43"
print(Array(price.utf8))
NumberFormatter
print(Array(price.utf8))
price
let priceWithoutComma = price.components(seperatedBy: [","]).joined()