Swift无法将NSNumber桥接到Int

时间:2018-05-09 16:59:09

标签: ios swift

我在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:file /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)

我无法理解这个问题的类型

2 个答案:

答案 0 :(得分:0)

您没有在问题中包含该号码的值,因此我无法确认这100%。但是,既然你说它在新设备上工作正常但在iPhone 5上失败了,我认为你正在处理32位和64位问题。

如果你谷歌这个,你会发现以下内容:

  

从2013年的iPhone 5S和iPad Air开始,全部是Apple的   iPhone,iPad和iPod已经包含了64位芯片。

根据Swift文档:link

  

Int在大多数情况下,您不需要选择特定大小的整数   在你的代码中使用。 Swift提供了一个额外的整数类型Int,   其大小与当前平台的原生单词大小相同:

     

在32位平台上,Int与Int32的大小相同。

     

在64位平台上,Int与Int64的大小相同。

     

除非您需要使用特定大小的整数,否则请始终使用   Int表示代码中的整数值。这有助于代码的一致性和   互操作性。即使在32位平台上,Int也可以存储任何值   介于-2,147,483,648和2,147,483,647之间,对许多人而言足够大   整数范围。

您的值是否超出32位Int范围?

答案 1 :(得分:0)

Swift 4使(new File(SUBDIRECTORY)).listFiles()更加严格。如果NSNumber无法由NSNumber表示,则演员会在运行时失败。
您可以将其强制转换为Int,但由于您提到仅在iPhone 5上失败,我们将安全地对其进行类型转换。

替换:

Double

使用:

let cost = String(history["price"] as! Int)