Nauman Ahmad
Nauman Ahmad

Reputation: 49

Can't pass data to another view controller in when preparing for segue

I am trying to pass an object to another view controller but I get an error when I try to set the property of the view controller object.

error_xcode

Upvotes: 0

Views: 251

Answers (3)

Laffen
Laffen

Reputation: 2771

The ViewController is obviously missing a string variable named data.

class ViewController : UIViewController {

    var data: String? // Make sure you have this defined in your view controller.
}

I would also suggest that you use a conditional unwrapping of the destinationViewController in your prepareForSegue.

prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if let viewController = segue.destinationViewController as? ViewController {

        viewController.data = "Hello World"
    }
}

For future posts, please refrain from posting images of code. You should include code as text in your questions.

Happy coding :)

The Basics

Upvotes: 2

Ahmed Onawale
Ahmed Onawale

Reputation: 4050

The error is pretty informative. It says the class ViewController has no public or internal property called data. You'll have to declare a property called data in class ViewController.

class ViewController: UIViewController {

  var data: String?

}

Upvotes: 3

tskippe
tskippe

Reputation: 165

the class you have that is named ViewController needs to have a public variable named data.

Your ViewController class could look something like this:

class ViewController: UIViewController {

    // This is your public accessible variable you can set during a seque
    var data: String?

    override func loadView() {
        super.loadView()
        print(self.data)
    }

}

Also, your prepareForSegue function can be simplified like this

if let displayTodoVC = segue.destinationViewController as? ViewController {
    displayTodoVC.data = "Hello World"
}

Upvotes: 2

Related Questions