Reputation: 396
I receive a result from JSONrequest where one attribute is normally a string but unfortunately sometimes is 0 (not a string). In order to process the JSON result I would like to check on whether it is a 0 or a string to avoid a crash
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 somebody can help to point me in the right direction I would be very greatful, I am a beginner in Swift and Xcode
Upvotes: 3
Views: 1479
Reputation: 4749
check with as?
keyword.
let index = record.value(forKey:"index") as? Int ?? -1
let id = record.value(forKey:"id") as? Int ?? "dummy value"
Upvotes: 0
Reputation: 11939
While Parsing this JSON you can implemented a check like this to avoid crash and to parse data from JSON is
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 parent variable will have string value while it will be a 0(Int) or a key(String) received from JOSN.
Upvotes: 3