实例成员不能用于类型 'ViewController'

Instance member cannot be used on type '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 的问题。目前我只是想让应用程序随机绘制一个字符串,但我收到一条错误消息:

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

在我声明变量的那一行 randomIndex。我使用 google 有一段时间了,但还没有找到解决方法。希望有人能帮忙,谢谢!

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

如果您粘贴的代码未在类似 viewDidLoad 的方法中定义,则您不能将在 class 级别定义的变量用于在 class 级别定义的另一个变量水平也是如此。这些变量是在 运行 时间确定的,并且它们确定的顺序是未知的,因此在生成 randomIndex 之前 fortuneArray 可能不存在(在幕后可能不是这样工作的,但你至少可以这样想)

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

啊,我在 Fonix 的帮助下弄明白了。我在 IBAction 中声明了随机数,它处理了它。