Expected declaration error for making high score

后端 未结 2 481
旧巷少年郎
旧巷少年郎 2020-12-07 06:45

I\'m trying to make a little game, now I want to make it possible to see the high score of the game. At the first UIViewController (viewcontroller1) you can see

相关标签:
2条回答
  • 2020-12-07 07:03

    To be clear for rookies like me, you can get the expected declaration error when you try to use a variable in your ViewController not in a function.

    For example this code will give you the expected declaration error.

    class ViewController: UIViewController {
    
        var savedText = ""
        savedText = "this" //<- Expected declaration error
    

    While this code will not give you the error.

    class ViewController: UIViewController {
    
        var savedText = ""
    
        override func viewDidLoad() {
            super.viewDidLoad()
            savedText = "this" //<- No error here because you used it in a function
    
    0 讨论(0)
  • 2020-12-07 07:26

    You are getting this error because you have the code in the wrong place in the class so move it to any function or in viewDidLoad method.

    You can have only declarations in class scope, not expressions to be executed.

    And it will work fine.

    EDIT: In your second UIViewController just read highScore from NSUserDefaults this way:

    let hScore = NSUserDefaults.standardUserDefaults().objectForKey("Highscore") as! String
    highSchoreLabel.text = hScore
    
    0 讨论(0)
提交回复
热议问题