[英]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? dataPass中是否有任何数据? If you don't assign any String to your dataPassed variable, and then you assign newVar to dataPassed, newVar will have nothing to print. 如果您未将任何String分配给dataPassed变量,然后将newVar分配给dataPassed,则newVar将没有任何内容可打印。
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. 其次,您似乎在尝试在函数之外再次println
。 That isn't going to work, because viewDidLoad is essentially the "main method" of your app. 那是行不通的,因为viewDidLoad本质上是应用程序的“主要方法”。 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. 您可以创建其他函数来响应按钮的触摸等,并在那里运行println,但是由于Swift代码是在功能上执行的,因此您执行的代码必须在特定的函数内部。 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. 无需功能即可独立运行Swift代码的唯一地方是Swift Playground。 In XCode you can select File -> New -> Playground to try this out. 在XCode中,您可以选择File-> New-> Playground尝试一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.