【问题标题】:Could not cast value of type 'NSTaggedPointerString' to 'NSNumber' - from PHP to Swift无法将“NSTaggedPointerString”类型的值转换为“NSNumber” - 从 PHP 到 Swift
【发布时间】:2017-11-14 15:54:27
【问题描述】:

我正在尝试将响应从 PHP 转换为 swift Dictionary,但我不知道该怎么做。

  1. 想知道为什么我使用 [String: [String: Int]] 不起作用。
  2. 尝试使用 NSDictionary,但不认为这是正确的方法,但似乎差不多了。

Swift 代码

Alamofire.request(requestString, method: .post, parameters: data, encoding:URLEncoding.default, headers: [:]).responseJSON { (response) in
    switch response.result {
        case .success(_):
            if let response = response.result.value as? [String: Any] {
                let updatedData = response["existData"] as! NSDictionary
                print(updatedData)
                let updatedData2 = response["existData"] as? [String: [String: Int]]
                print("updatedData2", updatedData2)
                var convertData = [String: [String: Int]]()
                for key in Array(updatedData.allKeys) {
                    var convertInsideData = [String: Int]()
                    if let array = updatedData[key] as? NSDictionary {
                        for (k, v) in array {
                            print(k, "-", v)
                            convertInsideData[k as! String] = v as! Int
                        }
                    }
                    convertData[key as! String] = convertInsideData
                }
       .....................

第一次打印,

{
    All =     {
        Maybelline = 2;
    };
}
updatedData2 Optional(["All": ["Maybelline": 2]])
Maybelline - 2

第二次打印,然后在convertInsideData[k as! String] = v as! Int崩溃

{
    All =     {
        Maybelline = 2;
        Sephora = 2;
    };
}
updatedData2 nil
Sephora - 2
Maybelline - 2
Could not cast value of type 'NSTaggedPointerString' (0x10e374c88) to 'NSNumber' (0x10d0ad600).
2017-11-14 23:52:04.939332+0800 LeanCloudStarter[10014:272299] Could not cast value of type 'NSTaggedPointerString' (0x10e374c88) to 'NSNumber' (0x10d0ad600).

PHP 的响应应该是这样的

$existData = array("All"=>array("Maybelline"=>2, "Sephora"=>2));
echo json_encode("existData"=>$existData));

【问题讨论】:

    标签: php ios swift type-conversion


    【解决方案1】:

    我建议你使用 optionals,那么你的 Int 值在你的 Json 中似乎是一个字符串,试试:

    for (k, v) in array {
        print(k, "-", v)
        if let stringV = v as? String {
            convertInsideData[k as! String] = Int(stringV)
        } else if let numberV = v as? NSNumber {
            convertInsideData[k as! String] = v.intValue
        }
    }
    

    【讨论】:

    • 遇到类似错误。 '无法将'__NSCFNumber'(0x10f77d008)类型的值转换为'NSString''
    • 我不能使用 if let 因为如果它是 nil 会丢失一些元素
    • 我已经编辑了我的答案,似乎有时你的 v 值是一个字符串,有时是一个 NSNumber。您可以添加 else 来检查 v 值是否为零。
    猜你喜欢
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 2017-06-01
    • 1970-01-01
    相关资源
    最近更新 更多