I recently started learning Swift, now I'm trying to safely unwrap multiple variables that come from a JSON response which might contain or not that key.
Example of the JSON response:
{
"products: [{
"foo": "foo"
"bar": "bar"
}, {
"foo": "foo"
}]
}
Here I'm trying the following:
let dataTask = URLSession.shared.dataTask(with: myURL) { (data, response, error) in
guard let safeData = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: safeData, options: .mutableLeaves)
if let jsonDict = json as? [String : Any] {
let productArray = jsonDict["products"] as? [[String : Any]]
for product in productArray! {
if let foo = product["foo"] as? String, let bar = product["bar"] as? String {
let prod = Product(foo: foo, bar: bar)
products.append(prod)
}
}
}
} catch {
print ("Error: \(error)")
}
}
What I want to do is to give bar
a default value (coalescing) if the value is nil, such as "Not Available"
in order to display it in a label.
Is it possible? How could I do that?