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
的那一行。我一直在使用谷歌一段时间,但没有找到解决办法。希望有人能帮忙,谢谢!
* 更新 * 问题解决了!谢谢。
最佳答案
如果您粘贴的代码未在类似 viewDidLoad
的方法中定义,则您也不能将在类级别定义的变量用于在类级别定义的另一个变量。这些变量是在运行时确定的,并且它们确定的顺序是未知的,因此在生成 randomIndex 之前 fortuneArray 可能不存在(在幕后可能不是真的这样工作,但你至少可以这样想)
您应该在 viewDidLoad
或 init
或其他函数中计算这些变量
关于ios - 实例成员不能用于类型 'ViewController',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34012063/