Pak Ho Cheung
Pak Ho Cheung

Reputation: 1416

Could not cast value of type 'NSTaggedPointerString' to 'NSNumber' - from PHP to Swift

I am trying to convert response from PHP to swift Dictionary but I couldn't figure out how to do it.

  1. Wondering why I use [String: [String: Int]] does not work.
  2. Tried to use NSDictionary but don't think this is a correct way but it seems almost there.

Swift code

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
                }
       .....................

First print,

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

Second print, then crash in 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).

Response from PHP should be like this

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

Upvotes: 1

Views: 2079

Answers (1)

Francesco Deliro
Francesco Deliro

Reputation: 3939

I suggest you to use optionals, then your Int value seems to be a String in your Json, try:

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

Upvotes: 3

Related Questions