accessing variables created in the override func viewDidLoad() { super.viewDidLoad() function outside that function in swift

667 views Asked by At
import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var labelA: UILabel!
    @IBOutlet weak var labelB: UILabel!


    var dataPassed:String!
    var secondDataPassed:String!
    var newVar: String!
    var newVar2: String!

    override func viewDidLoad() {
        super.viewDidLoad()
        labelA.text = dataPassed
        labelB.text = secondDataPassed
        newVar = labelA.text
         println(newVar)
    }


 println(newVar) *** I can't access newVar outside override func viewDidLoad() { - Gives "expected declaration" Its driving me crazy!!!***

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
1

There are 1 answers

4
Gabriel Garrett On

Is there any data in dataPassed? If you don't assign any String to your dataPassed variable, and then you assign newVar to dataPassed, newVar will have nothing to print.

Try:

    import UIKit

   class SecondViewController: UIViewController {
    @IBOutlet weak var labelA: UILabel!
    @IBOutlet weak var labelB: UILabel!


    var dataPassed:String! = "Test."
    var secondDataPassed:String!
    var newVar: String!
    var newVar2: String!

    override func viewDidLoad() {
        super.viewDidLoad()
        labelA.text = dataPassed
        labelB.text = secondDataPassed
        newVar = labelA.text
         println(newVar)
    }

Secondly, it appears that you're trying to println again outside of the function. That isn't going to work, because viewDidLoad is essentially the "main method" of your app. You can create other functions that respond to button touches, etc... and run a println there, but because Swift code is executed functionally, the code you're executing has to be inside of a particular function. While you can declare variables, as you have, you can't perform actions such as printing them outside of a function, because then there's no order/method to the madness.

The only place where you can run Swift code on a standalone basis without functions is in a Swift Playground. In XCode you can select File -> New -> Playground to try this out.