How to determine between string and integer received from JSON in Swift 3

I am getting the result from JSONrequest where one attribute is usually a string, but unfortunately sometimes it is 0 (not a string). To process the JSON result, I would like to check if it is 0 or a string to avoid crashing

part of the JSON result:

"9919ee1e-ffbc-480b-bc4b-77fb047e9e68" =         {
        icon = home;
        id = "9919ee1e-ffbc-480b-bc4b-77fb047e9e68";
        index = 1;
        name = Thuis;
        parent = 0;
    };
    "9eb2975d-49ea-4033-8db0-105a3e982117" =         {
        icon = books;
        id = "9eb2975d-49ea-4033-8db0-105a3e982117";
        index = 6;
        name = Studeerkamer;
        parent = "9919ee1e-ffbc-480b-bc4b-77fb047e9e68";
    };
    "a4a23044-edce-4b81-be7f-a2123e14d8c0" =         {
        icon = kitchen;
        id = "a4a23044-edce-4b81-be7f-a2123e14d8c0";
        index = 1;
        name = Keuken;
        parent = "855113f1-f488-4223-b675-2f01270f573e";
    };

      

Notice the parent attribute, which is the attribute I am referring to. If anyone can help me point me in the right direction I would be very kind, I am new to Swift and Xcode

+3


source to share


2 answers


When parsing this JSON, you can implement a validation like this to avoid crashing and parse the data from JSON

var parent:String?

if let parentId = dict.value(forKey:"parent") as? Int {
    parent = "\(parentId)"
} else if let parentId = dict.value(forKey:"parent") as? String {
   parent =  parentId
}

      



With this variable, the parent variable will have a string value as long as it is 0 (Int) or the key (String) obtained from JOSN.

+2


source


check the box with the keyword as?

.



let index = record.value(forKey:"index") as? Int ?? -1
let id = record.value(forKey:"id") as? Int ?? "dummy value"

      

0


source







All Articles