Search code examples
swiftuitableviewtableviewviewcontroller

Cannot assign value of type 'String' to type 'UILabel'


I am trying to pass data from tableview to another page (view controller) but problem is i am getting an error from tableview. Below is the code and i have marked the error where i am getting.

P1ViewController.Swift

class P1ViewController: ViewController,UITableViewDelegate,UITableViewDataSource {
    var name=["Table1","Table2"]
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return name.count
    } 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: "cell")
        cell?.textLabel?.text=name[indexPath.row]
        return cell!
    } 
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let detail=self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        detail.lblName=name[indexPath.row] //This is the error i am getting "Cannot assign value of type 'String' to type 'UILabel'"
        self.navigationController?.pushViewController(detail, animated: true)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

DetailViewController.Swift

class DetailViewController: ViewController {
    @IBOutlet weak var lblName: UILabel!
    var name:String!
    override func viewDidLoad() {
        super.viewDidLoad()
        lblName.text=name
    }
}

Solution

  • Actually you would have to write

    detail.lblName.text = name[indexPath.row] 
    

    but this will cause a crash. Assign the value to the name property

    detail.name = name[indexPath.row]