1

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?

Frakcool
  • 10,915
  • 9
  • 50
  • 89

2 Answers2

2

You can try

 let prod = Product(foo:product["foo"] as? String ?? "Not Available" , bar: product["bar"] as? String ?? "Not Available" )

struct Root: Decodable {
    let products: [Product]
}

struct Product: Decodable {
    let foo: String
    let bar: String?

    enum CodingKeys: String, CodingKey {
        case foo , bar  
    }

    init(from decoder: Decoder) throws {

         let container = try decoder.container(keyedBy: CodingKeys.self)


        do { 
            let foo = try container.decode(String.self, forKey: .foo)  
            let bar = try container.decodeIfPresent(String.self, forKey: .bar) ?? "Not Available"
            self.init(foo:foo, bar:bar)

        } catch let error {
            print(error)
            throw error
        }
     }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

As the Keys in json are Decodable friendly, you can use this minimal code,

struct ProductResponse: Decodable {
    let products: [Product]
}

struct Product: Decodable {
    let foo: String
    let bar: String?
}

let dataTask = URLSession.shared.dataTask(with: myURL) { (data, response, error) in
    guard let data = data else { return }

    do {
        let productResponse = JSONDecoder().decode(ProductResponse.self, from: data)
        print(productResponse.products.forEach({ print($0.foo)}))
    } catch {
        print ("Error: \(error)")
    }
}

Assigning a default value to bar at parsing level doesn't seem natural. Product is a simple type with just two properties but for a type with tens of properties you will hate implementing the init(from decoder: Decoder) and CodingKeys enumerations just because of one or two properties that need a default value.

I would suggest a better approach by introducing an extension to Optional as below,

extension Optional where Wrapped == String {

    /// Unwrapped string
    /// `u7d` comes from starting `u` in `Unwrapped`, 
    ///  7 letters in between and last letter `d`.
    public func u7d(_ defaultString: String = "N/A") -> String {
        guard let value = self, value.isEmpty == false else { return defaultString }
        return value
    }
}

So now when you want to use a default value if this property is nil, you can just unwrap by passing that default value as below,

productResponse.products.forEach({ product in
    print(product.bar.u7d("Not Available"))
})

This has some key benefits as below,

  • Your if statement result will stay as expected when you will compare this optional property with nil.
  • You can pass different default values at different places without any if statement.
  • As UITextField, UITextView and UILabel accept Optional text and in many cases you will need to show a placeholder when the string attribute is nil from the api response. So in those cases you don't have to re-engineer the string attribute to know if it has default value or api returned value.
Kamran
  • 14,987
  • 4
  • 33
  • 51