0

My task is I am trying to get keys and values from JSON response and load into tableView. Its like a billing UI left side list of fee names and right side It's prices. Keys pricenames and Values It prices

Here, my problem is I am receiving zero prices for some pricenames, If I received zero value I dont show that value and relevant key name in tableView.

If I load directly JSON to TableView list of price name first letter should be capital but JSON response only small providing. So, I decided to show static names(we don't add new name) and JSON price value. I would like to learn which is best solution for my problem and how to fix this?

// JSON Struct
struct Item : Codable {
    var name : String
    var price : String    
    init(name: String, price: String) {
        self.name = name
        self.price = price
    }
}

// Array Declarations
var billing_array = [Item]()

// JSON Parsing
if let results = result["result"] as? [String: AnyObject] {
    self.billing_array.append(results)
}

// TableView Delegation
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.billing_array.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
    let item = billing_array[indexPath.row]
        cell.product_name.text = item.name
        cell.product_price.text = item.price
    return cell
}
pastelsdev
  • 145
  • 1
  • 14
  • 1
    Please post the real code. The *Array Declarations* lines don't compile. Multiple arrays as data source are the worst choice. Use a custom struct which contains all data of **one** product respectively. – vadian Oct 08 '18 at 17:34
  • Take a look at the new JSON parsing capabilities of Swift 4 using `Codable`! That will make your life easier. – Barns Oct 08 '18 at 17:37
  • In a struct you can use optionals or default values. – vadian Oct 08 '18 at 17:39
  • Please [search](https://stackoverflow.com/search?q=%5Bswift%5D+parse+codable). Without knowing the JSON it's not reasonable to suggest something. – vadian Oct 08 '18 at 17:45
  • I updated my post. Please check it @vadian – pastelsdev Oct 08 '18 at 18:05
  • "If I received zero value I dont show that value and relevant key name in tableView": Well, when this happen, just don't append the `Item` to your array. "price name first letter should be capital": Use this https://stackoverflow.com/questions/26306326/swift-apply-uppercasestring-to-only-the-first-letter-of-a-string on `item.name` just before doing `cell.product_name.text = item.name`. – Larme Oct 08 '18 at 19:00

0 Answers0