How to convert value of type 'Int' to type 'IndexPath' in coercion

Helo,


I'm trying to make this for loop work, however I can't seam to solve this error, "Cannot convert value of type 'Int' to type 'IndexPath' in coercion"


Here's the code:

for i in 0...numOfRunners {
     var currentCell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: i as IndexPath) as! TableViewCellSetUp
            
     // Do Something with current cell    
}


I've tried numerous things I know, but nothing worked.


Many Thanks.

You'll need to create an IndexPath to pass to the dequeue function.


for i in 0 ..< numOfRunners {
    let indexPath = IndexPath(row: i, section: 0) // assuming cell is for first or only section of table view
    let currentCell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath) as! TableViewCellSetUp

    // Do Something with current cell
}


Note that I changed your closed range to a half-open range.

Would you have an idea for this code isn't working.


@IBAction func btnStart(_ sender: UIButton) {
        for i in 0..<numOfRunners {
            let indexPath = IndexPath(row: i, section: 0) 
            let currentCell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath) as! TableViewCellSetUp
            /
            if currentCell.txtFieldName.hasText != true {
                print("checked \(indexPath)")
                let alert = UIAlertController(title: "Warning!", message: "Please enter the number of runners", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
        }
    }


When I click the button, btnStart, the Alert message is displayed even when the textFields have text inside it. I, however, want the Alert message to display only, and only if, there is no text in the textField of a cell. So, When btnStart is clicked it should segue to next view.

I suppose txtFieldName is a property you have defined ? How ?


You should use text property instead


if !currentCell.text!.hasText { // Note : no need of != true

Accepted Answer

The cells being dequeued will not be the cells currently visible in your table view, so the dequeued cells' text fields won't contain the text that I think you're expecting to be in them. Don't consider table view cells as data storage. Instead, store data elsewhere (in arrays, for example) and only use the table view to present that data and accept input from users which can be used to update the stored data. The decision to display an alert or segue to the next scene can then be made according to the stored data.

How to convert value of type 'Int' to type 'IndexPath' in coercion
 
 
Q