Reputation: 47
The general purpose of converting an Int into a String is to display a "Score", which is incremented by one, every time a SKSpriteNode is tapped. The gesture is recognized by my GameScene class in GameScene.swift. It then uses a struct named "variables" to send the "Score" to my GameViewController which will display the score via UILabel. This is were I need to convert the Int into a String. Simple. Except every method I've tried has ended with the error: fatal error: unexpectedly found nil while unwrapping an Optional value. Furthermore, whenever I try to treat "Score" as an optional (add a '?') XCode gives me another error and tells me to remove it.
TL;DR: I need to convert an Int into a String, and all the methods that usually work aren't.
Method's I've tried:
scoreLabel.text = NSNumber(integer: Score).stringValue
scoreLabel.text = "\(Score)"
scoreLabel.text = String(Score)
scoreLabel.text = toString(Score)
scoreLabel.text = "\(Score.description)"
scoreLabel.text = Score.description
scoreLabel.text = "\(NSNumber(integer: Score).stringValue)"
I've also restarted XCode and Mac. Have I missed something obvious? Please help a noob out.
EDIT #1: I forgot to mention that I've been logging "Score" in both GameScene.swift and GameViewController.swift; both return the correct value.
Upvotes: 2
Views: 2370
Reputation: 259
The error you are receiving isn't because of the proper code, its because your "Score" variable is nil. What I always use is ->
scoreLabel.text = "\(Score)"
Then, set your the value of your "Score" to 0 so its value can't be returned nil.
var Score : Int = 0
Finally, to display the score, you should use an SKLabelNode.
var scoreLabel = SKLabelNode(fontNamed: "American Typewriter")
Then, in your didMove(toView)
override func didMove(to view: SKView) {
scoreLabel.text = "\(Score)"
scoreLabel.fontColor = UIColor.green
scoreLabel.fontSize = 30
scoreLabel.position = CGPoint(x: 0, y: self.frame.height / 4)
self.addChild(scoreLabel)
}
Upvotes: 1
Reputation: 1957
Try this :
let cast_this_optional_integer = Int(Score!)
print(String(cast_this_optional_integer))
Upvotes: 0
Reputation: 7582
Problem is swift checking type. You declare an optional value and when you use it. You need force it not nil.
// declare optional variable
var score: Int?
// Use it when you sure not nil
yourLabel.text = String(score!)
I advice you need to set initial value.
var score: Int = 0
And use it.
yourLabel.text = String(score)
Upvotes: 1
Reputation: 47
As Abdul Ahmad suggested, I should use a SKLabelNode rather than a UILabel to display my score because I'm doing so from a subclass of SKScene. I don't know why the value couldn't be converted in my other class (as Aderis pointed out, all my methods should've worked), as I was able to log it using the same syntax and methods I was using to attempt to set the UILabel's text.
To any future googlers with the same problem:
Upvotes: 1