Swift 无法使用常规方法将 Int 转换为 String

Swift Cannot convert Int to String with usual methods

Int转String的一般目的是显示一个"Score",每点击一个SKSpriteNode就加1。我的 GameScene class 在 GameScene.swift 中识别该手势。然后它使用名为 "variables" 的结构将 "Score" 发送到我的 GameViewController,它将通过 UILabel 显示分数。这是我需要将 Int 转换为 String。简单的。除了我尝试过的每种方法都以错误结束:致命错误:在展开可选值 时意外发现 nil。此外,每当我尝试将 "Score" 视为可选项(添加“?”)时,XCode 都会给我另一个错误并告诉我将其删除。

TL;DR: 我需要将 Int 转换为 String,而所有通常有效的方法都无效。

我试过的方法:

  1. scoreLabel.text = NSNumber(integer: Score).stringValue
  2. scoreLabel.text = "\(Score)"
  3. scoreLabel.text = String(Score)
  4. scoreLabel.text = toString(Score)
  5. scoreLabel.text = "\(Score.description)"
  6. scoreLabel.text = Score.description
  7. scoreLabel.text = "\(NSNumber(integer: Score).stringValue)"

我还重新启动了 XCode 和 Mac。我错过了一些明显的东西吗?请帮助菜鸟。

编辑 #1:我忘了说我一直在 GameScene.swift 和 GameViewController.swift 中记录 "Score"; return 都是正确的值。

正如 Abdul Ahmad 所建议的,我应该使用 SKLabelNode 而不是 UILabel 来显示我的分数,因为我是从 SKScene 的子class 这样做的。我不知道为什么这个值不能在我的另一个 class 中转换(正如 Aderis 指出的那样,我所有的方法都应该有效),因为我能够使用与我相同的语法和方法记录它用于尝试设置 UILabel 的文本。


致未来遇到同样问题的所有 google 员工:

  1. 检查你的语法
  2. 记录它可能更改的每个点的值
  3. 尝试使用类似的 classes? (我使用 SKScene 来更改 SKLabelNode 而不是 UILabel 的文本)

问题是 swift 检查类型。您声明一个可选值以及何时使用它。你需要强制它不为零。

// declare optional variable
var score: Int?

// Use it when you sure not nil
yourLabel.text = String(score!)

我建议你需要设置初始值。

var score: Int = 0

并使用它。

yourLabel.text = String(score)

试试这个:

    let cast_this_optional_integer = Int(Score!)
    print(String(cast_this_optional_integer))

您收到的错误不是因为代码不正确,而是因为您的 "Score" 变量为 nil。我经常使用的是 ->

scoreLabel.text = "\(Score)"

然后,将 "Score" 的值设置为 0,这样它的值就不会返回 nil。

var Score : Int = 0

最后,要显示分数,您应该使用 SKLabelNode。

var scoreLabel = SKLabelNode(fontNamed: "American Typewriter")

然后,在您的 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)
}