I am trying to cal the let name statement inside struct person from twoVIEWCONTROLLER. I thought I can just call a structs entries from another view controller but I am not sure. You can see in twoVIEWCONTROLLER i have “l.text =”. I tried l.text = person.name but that does not work.
VIEWCONTROLLER
import UIKit
class ViewController: UIViewController {
@IBOutlet var a: UITextField!
@IBOutlet var label: UILabel!
var contacts = [Person]()
@IBAction func save(_ sender: Any) {
contacts.append(Person(name: a.text!))
contacts.sort { $0.name < $1.name }
}}
struct Person: CustomStringConvertible {
let name: String
var description: String {
return name
}}
twoVIEWCONTROLLER
import UIKit
class twoViewController: UIViewController {
@IBOutlet var l: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
l.text =
}}
It isn’t complete solution, but it will give you an idea
class twoViewController: UIViewController {
@IBOutlet var l: UILabel!
//TODO: get referanceToOtherViewController with some logic
//TODO: comment this line and uncomment the next one
var referanceToOtherViewController: ViewController? = ViewController()
// weak var referanceToOtherViewController: ViewController?
override func viewDidLoad() {
super.viewDidLoad()
addAPersonOnOtherVCWhenUsingPlaygroundInsteadOfBuildingVCs()
let text = referanceToOtherViewController?.contacts.first?.name
print(text) // Jhon Silver
l.text = referanceToOtherViewController?.contacts.first?.name
}
// using this instead of running in Simulator
func addAPersonOnOtherVCWhenUsingPlaygroundInsteadOfBuildingVCs() {
let newPerson = Person(name: "Jhon Silver")
referanceToOtherViewController?.contacts.append(newPerson)
}
}
Thanks for the response @ofiron! Anyway the code is not transferring the value from vc to vc2. When I applied your code “Jhon Silver” is always on vc2 but whatever I enter into vc is not being transferred.
Thanks ofiron, I agree that the solution you proposed is absolutely the correct way to pass a variable between 2 view controllers (and to suggest anything else, is not in any way beneficial). You however can use a struct to pass variables between different classes (useful if using mvc architecture), but the way it was written meant that person.name was constantly seen as “”, and because the variable is wrapped in a struct Xcode struggles to pick up this up. Sorry for the confusion, and thank you for the reply.