首页 > 解决方案 > 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)

我不明白这是什么类型的问题

标签: iosswift

解决方案


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)"
}

推荐阅读