-4

How can i convert labels to integers and sum all of them up

    var totalCount:Int?
    if let number = Int(price.text!) {
        let myNumber = NSNumber(integer:number)
        totalCount = totalCount! + myNumber.integerValue
        print(totalCount)
    } else {
        print("'\(price.text)' did not convert to an Int")
    }

here is my code it is not working

lordxxx
  • 49
  • 1
  • 8

2 Answers2

3

Use this method.

var totalCount = 0
guard let priceString = price.text else {
   print("price label is nil")
   return
}
let myNumber = Int(priceString)
totalCount = totalCount + myNumber!
print(totalCount)
Ioan Moldovan
  • 2,272
  • 2
  • 29
  • 54
0

Brother I tried your coding first it shows me the error when run time on this line

totalCount = totalCount! + myNumber.integerValue

fatal error: unexpectedly found nil while unwrapping an Optional value

Then I set

var totalCount:Int = 0
var arr = [String]()

The tried sample coding is

override func viewDidLoad()
{
   super.viewDidLoad()
   var totalCount:Int = 0
   let priceValue: String = "100"
   arr.append(priceValue)
   self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

}

Then in tableView delegate methods

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arr.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{
    let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!

    let priceVal = arr[indexPath.row]
    if let number = Int(priceVal)
    {
        let myNumber = NSNumber(integer:number)
        totalCount =  totalCount  + myNumber.integerValue
        print(totalCount)
    }
    else
    {
       print("'\(priceVal)' did not convert to an Int")
    }

    cell.textLabel?.text = String(totalCount)

    return cell
}

Printed result is

100

Community wiki group answered

Community
  • 1
  • 1
user3182143
  • 9,459
  • 3
  • 32
  • 39