我正在尝试初始化要在整个程序中使用的变量,但是如何在viewDidLoad()函数之外执行此操作。
目前变量“wordToUse”在viewDidLoad()函数中声明但是我无法在程序的其他地方访问它以与按下按钮时进行比较,因此如何声明它以便它可以初始化一次程序已启动,然后在整个程序中使用?
这是我的代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var wordLabel: UILabel!
@IBOutlet weak var lettersUsed: UILabel!
var lives = 5
var wordList = ["Watch", "Phone", "Apple", "Technology", "Swift", "Computing", "Software", "Hardware", "Computers", "Processor", "Swift", "Java", "Python", "Programming", "Development", "Microsoft", "DropBox", "Facebook"]
var wordToUse: String {
println(wordList[Int(arc4random_uniform(18))])
return wordList[Int(arc4random_uniform(18))]
}
override func viewDidLoad() {
super.viewDidLoad()
var wordToUseList = Array(wordToUse)
for var index = 0; index != wordToUseList.count; ++index {
wordToUseList[index] = "*"
}
wordLabel.text = String(wordToUseList)
println(wordToUseList)
livesText.text = String(lives)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
答案 0 :(得分:4)
您想拥有一个全局变量。所以你只需在类声明之外声明它:
var wordList = ["Watch", "Phone", "Apple", "Technology", "Swift", "Computing", "Software", "Hardware", "Computers", "Processor", "Swift", "Java", "Python", "Programming", "Development", "Microsoft", "DropBox", "Facebook"]
var wordToUse: String {
println(wordList[Int(arc4random_uniform(18))])
return wordList[Int(arc4random_uniform(18))]
}
class ViewController: UIViewController {
...
}