You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift类型转换错误:__NSCFNumber转NSString失败,求正确方法

解决Swift中__NSCFNumber转NSString的类型转换错误

嘿,这个问题我之前也碰到过!你遇到的崩溃是因为接口返回的wallet_amount是数字类型(底层是__NSCFNumber,对应Swift里的NSNumber/Int/Double),但你直接用as! String强制转换成字符串,这就导致了类型不匹配的崩溃。

数字转字符串的正确方式

你需要先把这个值转换成Swift的数值类型(或NSNumber),再转换成字符串,同时推荐用可选绑定替代强制解包,避免潜在的崩溃:

方式1:通过NSNumber的stringValue转换

这是最直接的方式,适合不确定数值类型(可能是Int或Double)的场景:

if let walletAmount = result["wallet_amount"] as? NSNumber {
    let walletString = walletAmount.stringValue
    self.labelWallet.text = "\(AppDelegate.appDelegateObject().localLanguage(key: "available_money", comment: "")) \(walletString) €"
    self.stringWallet = walletString
}

方式2:转换成Swift原生数值类型后转字符串

如果你确定接口返回的是整数或浮点数,可以直接转成对应的Swift类型,还能自定义格式(比如保留小数位数):

// 如果是整数
if let walletAmount = result["wallet_amount"] as? Int {
    let walletString = String(walletAmount)
    self.labelWallet.text = "\(AppDelegate.appDelegateObject().localLanguage(key: "available_money", comment: "")) \(walletString) €"
    self.stringWallet = walletString
}

// 如果是浮点数,且需要保留两位小数
if let walletAmount = result["wallet_amount"] as? Double {
    let walletString = String(format: "%.2f", walletAmount)
    self.labelWallet.text = "\(AppDelegate.appDelegateObject().localLanguage(key: "available_money", comment: "")) \(walletString) €"
    self.stringWallet = walletString
}

修改后的完整getDistrictList函数片段

把你原来的代码中处理wallet_amount的部分替换成上面的写法,修改后的代码如下:

func getDistrictList() -> Void {
    let reachable = Reachability()!
    let tempDict = NSMutableDictionary()
    let user = UserDefaults.standard.object(forKey: "user_data") as! NSDictionary
    tempDict.setValue(user.object(forKey:"user_id")!, forKey: "user_id")
    tempDict.setValue(AppDelegate.appDelegateObject().languageToSend(), forKey: "lang_code")
    
    if reachable.isReachable {
        Services.requestForUpdatedWallet(postDic: tempDict, completion: { (result) in
            let isSuccess = result["success"] as! Bool
            if isSuccess {
                DispatchQueue.main.sync {
                    if let walletAmount = result["wallet_amount"] as? NSNumber {
                        let walletString = walletAmount.stringValue
                        self.labelWallet.text = "\(AppDelegate.appDelegateObject().localLanguage(key: "available_money", comment: "")) \(walletString) €"
                        self.stringWallet = walletString
                    } else {
                        self.labelWallet.text = "\(AppDelegate.appDelegateObject().localLanguage(key: "available_money", comment: "")) 0 €"
                        self.stringWallet = "0"
                    }
                    MBProgressHUD.hideAllHUDs(for: self.view, animated: true)
                    // self.tblDistrict.reloadData()
                }
            }
        })
    } 
    // else{ 
    //     self.showAlert(title: AppDelegate.appDelegateObject().localLanguage(key: "app_name", comment: ""), message: AppDelegate.appDelegateObject().localLanguage(key: "no_internet", comment: "")) 
    // }
}

额外提醒

  • 尽量避免使用as!强制解包,一旦接口返回的类型或数据不符合预期,就会导致崩溃,用as?配合可选绑定更安全。
  • 如果需要处理不同的数值类型(比如可能返回Int或Double),用NSNumber的方式兼容性更好。

内容的提问来源于stack exchange,提问作者Somdeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:36:36