![](/img/trans.png)
[英]Swift function works in app but not within override func viewDidLoad()
[英]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.
}
}
dataPass中是否有任何數據? 如果您未將任何String分配給dataPassed變量,然后將newVar分配給dataPassed,則newVar將沒有任何內容可打印。
嘗試:
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)
}
其次,您似乎在嘗試在函數之外再次println
。 那是行不通的,因為viewDidLoad本質上是應用程序的“主要方法”。 您可以創建其他函數來響應按鈕的觸摸等,並在那里運行println,但是由於Swift代碼是在功能上執行的,因此您執行的代碼必須在特定的函數內部。 盡管可以聲明變量,但不能執行諸如在函數外部打印變量的操作,因為這樣就沒有瘋狂的順序/方法了。
無需功能即可獨立運行Swift代碼的唯一地方是Swift Playground。 在XCode中,您可以選擇File-> New-> Playground嘗試一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.