Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

ios - 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]

}

I'm creating a very simple fortune telling app in Swift and I keep running into issues with arc4random_uniform. Currently I'm just trying to get the app to draw a string at random but I get an error saying:

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

on the line where I am declaring the variable randomIndex. I've been using google for awhile but haven't found a fix. Hopefully someone can help, thanks!

* Update * Problem solved! Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If the code you pasted is not defined in a method like viewDidLoad, you cannot use a variable thats defined at the class level for another variable thats defined at the class level as well. These variables are determined at run time and the order they are determined is not known so fortuneArray may not exist before randomIndex is made (might not really work like this behind the scenes but you can think of it this way at least)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...