Search code examples
iosswiftuipickerview

How To Set Total1 And Total2 Value Into Label When User Scrolls on Both Segment Of picker View (Dynamically)?


func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    if component == 0 {
        lbl1.text = pdata[0][row]
        lbl1.adjustsFontSizeToFitWidth = true
        img1.image = UIImage(named : pdata[0][row])
        price1.text = priceData[row]
        total1 = Int(priceData[row]) ?? 0

        }

 else if component == 1 {
        lbl2.text = pdata[1][row]
        lbl2.adjustsFontSizeToFitWidth = true
        img2.image = UIImage(named : imgdata[row])
        price2.text = PriceData2[row]
        total2 = Int(PriceData2[row]) ?? 0

    }

   TotalPrice.text = String(total1! + total2!)



}

When user scroll on 1 Segment then total becomes nil and app crashes how can I store both total 1 and total 2 variable to show sum of price to user


Solution

  • You can use coalescing operator to prevent force unwrap:

    TotalPrice.text = String((total1 ?? 0) + (total2 ?? 0))
    

    https://en.wikipedia.org/wiki/Null_coalescing_operator