Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ios - Expected declaration error for making high score

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 the score (UILabel called ourScore) and the score is working with (var score: String!). The score has been connected to a label called recentScore at the other UIViewController (viewcontroller2) With the use of

override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) {
        if (segue.identifier == "segueTest") {
            var svc = segue!.destinationViewController as! PointsViewController;
       }
}

the score will connect to the other label at the other UIViewController (2) to see the final score. Now I wanted to make it possible to see also the high score. Currently the high score is with in the code the following on the first UIViewController

let highscore = ourScore.text;
NSUserDefaults.standardUserDefaults().setObject(highscore, forKey: "Highscore")
NSUserDefaults.standardUserDefaults().synchronize()

and at the other UIViewController it is:

highSchore.text = NSUserDefaults.standardUserDefaults().stringForKey("Highscore")

highScore is currently the label in the second UIViewController where the high score should be showing, I got an error at the code

highSchore.text = NSUserDefaults.standardUserDefaults().stringForKey("Highscore")

In the above line, it says Expected declaration.

Thanks for the help!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...