Swift报错:Unable to bridge NSNumber to Int,仅iPhone 5出现异常
解决iPhone 5上NSNumber无法桥接为Int的崩溃问题
我来帮你分析下这个问题——崩溃只在iPhone 5上出现,核心原因是iPhone 5是32位设备,而你测试的其他设备(iPhone7、iPad系列)都是64位架构。
在Swift里,Int类型的位数是跟着设备走的:
- 64位设备上,
Int等价于Int64,能容纳更大的数值 - 32位设备上,
Int等价于Int32,最大值只有2^31 - 1(也就是2147483647)
服务器返回的price对应的NSNumber,如果数值超过了32位Int的上限,在iPhone 5上用as! Int强行转换时,就会触发“无法桥接NSNumber到Int”的致命错误——因为这个数值已经超出了当前Int类型能承载的范围。
修复方案
你需要替换掉不安全的强制转换,改用兼容32/64位的安全处理方式:
方案1:通过NSNumber获取64位整数(最稳妥)
// 替换原来的let cost = String(history["price"] as! Int) if let priceNumber = history["price"] as? NSNumber { // 用int64Value确保能容纳大数,不受设备位数限制 let cost = String(priceNumber.int64Value) cell.sumLbl?.text = String(cost.dropLast(2)) } else { // 处理数据异常的情况,给个默认值 cell.sumLbl?.text = "0" }
方案2:直接转换为Int64类型
if let price = history["price"] as? Int64 { let cost = String(price) cell.sumLbl?.text = String(cost.dropLast(2)) } else { cell.sumLbl?.text = "0" }
额外优化建议
你的代码里还有好几处as!强制解包(比如history["id"] as! Int),这些都是潜在的崩溃点——只要服务器返回的数据格式有一点异常,就会导致崩溃。建议统一改成可选绑定的方式,比如:
// 替换原来的cell.numberLbl?.text = String(history["id"] as! Int) if let id = history["id"] as? Int { cell.numberLbl?.text = String(id) } else { cell.numberLbl?.text = "" }
这样既解决了当前的iPhone 5崩溃问题,还能大幅提升代码的健壮性,避免其他因数据异常导致的崩溃。
内容的提问来源于stack exchange,提问作者Nazar
相关产品推荐
相关产品推荐

