Search code examples
swiftstringcastingsprite-kitint64

Swift Cannot construct string with argument type Int64


I am making a game that involves a Game Center leaderboard. I want to make a custom leaderboard UI rather than using the default interface.

I am trying to convert the values stored in a Game Center leaderboard into a string so that I may display them using an SKLabelNode. However, I get an error saying that:

Cannot invoke initializer for type 'String' with an argument list of type '(Int64?)'

I am accessing the Game Center scores using

leaderboard.scores[i].value

When I use the String(describing: ) method, my label node reads "optional(10)", with whatever the score is being inside the parenthesis. I am wondering how to cleanly convey the data store in Game Center into a number in string format.


Solution

  • Try optional binding:

    if let unwrapped = leaderboard.scores[i].value {
        let string = String(unwrapped)
        print(string)
    }
    

    Or use the guard statement if you want to use the unwrapped value in the rest of the scope:

    guard let unwrapped = leaderboard.scores[i].value else {
        fatalError("Couldn't unwrap the score value")
    }
    let string = String(unwrapped)