Accessing Variables from FirstViewController from SecondViewController in Swift

98 views Asked by At

I've been trying to access variables located within my FirstViewController class from the SecondViewController. I've tried instantiating the firstviewcontroller from the secondviewcontroller but I've having extreme troubles with this NSCoder deal, and no previous posts seem to be working... Most likely because Swift keeps getting 'updated' and breaks any old code or because I can't call it right...

My init code in FirstViewController is the following:

required init(coder aDecoder: NSCoder) {

    super.init(coder: aDecoder)
    fatalError("init(coder:) has not been implemented")
}

Any help right now would be amazing. Thanks

1

There are 1 answers

1
Mark McCorkle On

There are no differences in passing / setting values of objects from one class to another in Swift vs Objective C. Generally in modern Swift projects you will be using storyboards. However the idea is the same. At the time of instantiating your second viewController you would directly access that viewController's properties at that point. Generally when communicating back to the first viewController you would utilize a protocol / delegate scenario (research these). Below is a very simple example of accessing properties of a secondary viewController using the prepareForSegue function (storyboard defaults).

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if segue.identifier == "someidentifier" {
        let vc = segue.destinationViewController as MySecondViewController
        // vc.someProperty = someValue
    }
}

EDIT: Please check out this tutorial and similar ones. The key principle is segue.detinationViewController

http://makeapppie.com/2014/07/01/swift-swift-using-segues-and-delegates-in-navigation-controllers-part-1-the-template/