简体   繁体   中英

Swift - Alternative way to declare variable outside of viewDidLoad()

I'm trying to initialise a variable to be used in the whole of the program but how would you do this outside of the viewDidLoad() function.

Currently the variable "wordToUse" is declared in the viewDidLoad() function but then I can't access it elsewhere in the program to be compared with when a button is pressed so how can it be declared so that it can initialised once the program has started up and then used throughout the program?

Here's my code:

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()

}

You want to have a global variable. So you simply declare it outside the class declaration:

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

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