Instance item cannot be used for 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] } 

I am creating a very simple fortune-telling app in Swift, and I continue to run into problems with arc4random_uniform . I'm currently just trying to get the application to draw a string at random, but I get an error:

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

in the line where I declare the variable randomIndex . I have been using Google for a while but have not found a fix. Hope someone can help, thanks!

* Update * The problem is solved! Thanks.

+5
source share
2 answers

If the code you entered is not defined in a method of type viewDidLoad , you cannot use a variable defined at the class level for another variable that is also defined at the class level. These variables are defined at runtime, and the order that they determine is unknown, so fortuneArray may not exist until randomIndex is created (this may not work behind the scenes, but you can think of it this way, at least)

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

+10
source

Ah, I figured it out with Fonix. I declared a random number in IBAction and took care of that.

0
source

Source: https://habr.com/ru/post/1237148/


All Articles