ios - Swift 无法将 NSNumber 桥接到 Int
问题描述
我有UITableView
里面UIViewController
var userHistory: [[String: Any]] = [[String: Any]]()
override func viewDidLoad() {
Alamofire.request("http://...").responseJSON { (response) in
if let responseValue = response.result.value as! [String: Any]? {
if let responseFoods = responseValue["orders"] as! [[String: Any]]? {
self.userHistory = responseFoods
self.collectionView?.reloadData()
}
}
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "basCell", for: indexPath) as! BasCollectionViewCell
let history = userHistory[indexPath.row]
cell.numberLbl?.text = String(history["id"] as! Int)
cell.statusLbl?.text = (history["status"] as? String) ?? ""
let cost = String(history["price"] as! Int)
cell.sumLbl?.text = String(cost.dropLast(2)
cell.dateLbl?.text = (history["date"] as? String) ?? ""
return cell
}
问题是当我在模拟器、我的 iPad mini、iPad Pro、iPhone 7 上测试时 - 一切都很好,没有错误
但是当我在 iPhone 5 上启动时给我错误:
致命错误:无法将 NSNumber 桥接到 Int:文件 /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-902.0.48/src/swift/stdlib/public/SDK/Foundation/NSNumber.swift,第 367 行
和
线程 1:致命错误:无法将 NSNumber 桥接到 Int
对面的let cost = String(history["price"] as! Int)
我不明白这是什么类型的问题
解决方案
Swift 4 使NSNumber
桥接更加严格。如果NSNumber
不能由 表示Int
,则强制转换在运行时失败。
您可以Double
改为进行类型转换,但由于您提到这仅在 iPhone 5 上失败,我们将安全地为这两种情况进行类型转换。
代替:
let cost = String(history["price"] as! Int)
和:
var cost = ""
if let price = dict["price"] as? Int {
cost = "\(price)"
}
else if let price = dict["price"] as? Double {
cost = "\(price)"
}
推荐阅读
- java - 在一系列偏移量之间从 Kafka 主题读取消息
- vba - 无法在输入框中输入范围
- excel - 删除 AM/PM,但保留 12h 格式
- forms - 在 Flutter 中填写完表单中的所有字段后关闭键盘?
- python - 如何在python中将时间和时区转换为日期?
- typescript - TypeScript 从其他项目绝对导入普通 TS 文件和全局范围声明
- protocol-buffers - 如何在 gRPC 中使用标量类型作为函数参数?
- visual-studio-code - 删除触摸栏上预配置的 VSCode 按钮
- reactjs - 创建 React App - 无法获取本地颁发者证书
- c# - 如何执行 Graphql 查询?