Swift字符串转Double失败:数字字符串为何转为nil?
问题原因
你遇到的核心问题是从JSON解析得到的price字符串并非看起来的纯数字格式,大概率是以下两种情况之一:
- 字符串带有千位分隔符(比如实际是
"1,392.43",打印时视觉上容易忽略逗号):Swift原生Double(String)初始化器无法识别这种带格式的字符串,会返回nil;而NSString的doubleValue遇到非数字字符(逗号)就停止解析,只读取到1,所以得到1.0。 - 字符串前后包含不可见空白字符(如空格、换行符)或其他非标准字符,导致解析失败。
解决方案
推荐使用NumberFormatter解析带格式的数字字符串,它能处理千位分隔符、空白字符等场景,比原生初始化器更可靠。修改代码如下:
//MARK: - ExchangeManagerDelegate extension ViewController: ExchangeManagerDelegate { func didUpdateCurrency(price: String) { DispatchQueue.main.async { // 创建并配置数字格式化器 let formatter = NumberFormatter() formatter.numberStyle = .decimal // 设置区域适配欧美数字格式(根据JSON返回格式调整) formatter.locale = Locale(identifier: "en_US_POSIX") // 安全解析price字符串 guard let priceNumber = formatter.number(from: price) else { print("无法解析price字符串") return } let priceDouble = priceNumber.doubleValue print(priceDouble) // 输出1392.43 // 安全解析输入价格(避免强制解包崩溃) guard let inputText = self.currency1Price.text, let inputPrice = Double(inputText) else { print("输入价格无效") return } print(inputPrice) // 计算并显示结果 let result = priceDouble * inputPrice print(result) // 输出13924.3 self.currency2Price.text = String(format: "%.2f", result) } } func didFailWithError(error: Error) { print(error) } }
简化场景替代方案
如果确认JSON返回的数字格式简单,也可以先清理字符串中的非数字和小数点字符,再转Double:
let cleanedPrice = price.components(separatedBy: CharacterSet.decimalDigits.inverted).joined() let priceDouble = Double(cleanedPrice) ?? 0
但这种方法灵活性差,仅适合无复杂格式的场景。
内容的提问来源于stack exchange,提问作者Hoyeon Lee
相关产品推荐
相关产品推荐

