Nic*_* L. 11 random arc4random ios swift
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]
}
Run Code Online (Sandbox Code Playgroud)
我在Swift中创建了一个非常简单的算命应用程序,并且我一直在遇到问题arc4random_uniform
.目前我只是试图让应用程序随机绘制一个字符串,但我得到一个错误说:
实例成员'fortuneArray'不能用于'ViewController'类型
在我声明变量的行上randomIndex
.我已经使用谷歌一段时间但没有找到修复.希望有人可以提供帮助,谢谢!
*更新* 问题解决了!谢谢.
Fon*_*nix 17
如果您粘贴的代码未在类似方法中定义,则不能将在viewDidLoad
类级别定义的变量用于在类级别定义的另一个变量.这些变量是在运行时确定的,并且它们的确定顺序是未知的,因此在创建randomIndex之前可能不存在fortuneArray(在幕后可能不会像这样工作,但你至少可以这样思考)
你应该在内部viewDidLoad
或init
其他函数中计算这些变量