实例成员不能在'ViewController'类型上使用

问题描述:

class ViewController: UIViewController {    

let fortuneArray = ["You will find true love in the summer.", "Outlook not good", "You may find great success in business soon.", "Watch out for grey cats."]
let randomIndex = Int(arc4random_uniform(fortuneArray.count))

override func viewDidLoad() {
    super.viewDidLoad()
    let randomIndex = Int(arc4random_uniform(UInt32(fortuneArray.count)))
    print("random index: ")
    print(randomIndex)
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// actions
@IBAction func cookiePressed(sender: AnyObject) {
    fortune.text = fortuneArray[randomIndex]

}

我正在Swift中创建一个非常简单的算命应用程序,而我一直遇到 arc4random_uniform 。目前,我只是想让应用程序随机绘制一个字符串,但出现错误提示:

I'm creating a very simple fortune telling app in Swift and I keep running into issues with arc4random_uniform. Currently I'm just trying to get the app to draw a string at random but I get an error saying:


实例成员'fortuneArray'不能在我声明变量 randomIndex $的行上使用'ViewController'

Instance member 'fortuneArray' cannot be used on type 'ViewController'

c $ c>。我已经使用Google一段时间了,但是没有找到解决方法。希望有人能提供帮助,谢谢!

on the line where I am declaring the variable randomIndex. I've been using google for awhile but haven't found a fix. Hopefully someone can help, thanks!

*更新*
问题已解决!谢谢。

* Update * Problem solved! Thanks.

如果粘贴的代码未在 viewDidLoad $ c之类的方法中定义$ c>,您也不能将在类级别定义的一个变量也用于在类级别定义的另一个变量。这些变量是在运行时确定的,并且确定它们的顺序是未知的,因此fortuneArray在创建randomIndex之前可能不存在(在幕后可能无法真正起作用,但至少可以这样想)

If the code you pasted is not defined in a method like viewDidLoad, you cannot use a variable thats defined at the class level for another variable thats defined at the class level as well. These variables are determined at run time and the order they are determined is not known so fortuneArray may not exist before randomIndex is made (might not really work like this behind the scenes but you can think of it this way at least)

您应该在 viewDidLoad init 或其他函数中计算这些变量

you should compute these variables inside viewDidLoad or init or some other function instead