Call var from different class swift 4

I want to be able call var persons in vc2 to be displayed on a label in vc2 where it says l.text = . Thats if it is possible.

VC

                 import UIKit
class ViewController: UIViewController {
@IBOutlet var c: UITextField!
@IBOutlet var a: UITextField!
    var persons:[Person] = [Person]()

    @IBAction func save(_ sender: Any) {

  let judo = Person.init(name: a.text ?? "", phone: Int(c.text ?? "") ?? 0)
   self.persons.append(judo)

    }


    struct Person :  CustomStringConvertible  {
        var name: String
        var phone: Int
        static var myStruct = [String]();
        var description: String {
            return   "\(name),\(phone)"
        }}
    
}

VC2

       import UIKit

class twoViewController: UIViewController {
@IBOutlet var l: UILabel!
    override func viewDidLoad() {

        l.text = 


    }}

hi TimSwift,

There are a couple of ways to achieve this. Passing data between classes or more specifically between two view controllers is the most common problem faced by many developers when they start out.

The easiest way to achieve this is to have a reference to the second class from the first class, that way you can access all of the publicly available methods and properties.

The other way is to save it to a text file or UserDefaults and retrieve it. However, look at the lifecycle of the ViewControllers to ensure that you have saved the data before the next view controller retrieves the data.

Another way is to have a common Object, like the UserDefaults, a kind of a Clipboard/Object that can hold arbitrary data and ensure that this object is available on some global object/scope so you can access it easily.

If you google the term “pass data between two view controllers iOS” you should get plenty of resources. Hence I am not posting any code here to avoid duplicating that.

Cheers,

Jayant

This topic was automatically closed after 166 days. New replies are no longer allowed.