简体   繁体   中英

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

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.
    }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM