实例成员不能用于’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问题。 目前我只是试图让应用程序随机绘制一个字符串,但我得到一个错误说:

实例成员’fortuneArray’不能用于’ViewController’类型

在我声明变量randomIndex 。 我已经使用谷歌一段时间但没有找到修复。 希望有人可以提供帮助,谢谢!

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

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

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

啊,我在Fonix的帮助下弄清楚了。 我在IBAction中宣布了随机数并且处理了它。