How to Assign Value of Type Double to Type String?

Hey guys, I'm having a problem when attempting to display data from an API JSON feed in a tableview. While some of my functions are strings, others are double or int. Therefore, I get the error "Cannot assign value of type 'Double?' to type 'String?'" when attempting to display data in a double format. Also, it should be noted that this JSON feed has nested elements. How can I go about fixing this issue. For reference, the needed parts of my code are below.


JSON Struct

struct PlayerStatsParent:Decodable{
    let rankings: [PlayerStats]
}

struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}


Tableview Cell Function

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "rankCell") as? RankTableViewCell else { return UITableViewCell() }
        cell.nameLabel.text = rank[indexPath.row].score
}

Optional binding on "rank[indexPath.row].score" then create a string from the double value


if let value = rank[indexPath.row].score {
     cell.nameLabel.text = String(value)
} else {
     cell.nameLablel.text = "Free"
}

What iTen said plus…

If you’re displaying numbers to the user, you should use

NumberFormatter
to get a locale-aware string. For example:
let value: Double = 1234
let valueStr = NumberFormatter.localizedString(from: NSNumber(value: value), number: .decimal)
print(valueStr)     // prints "1,234" on /my/ system

On other user’s systems this might print:

  • 1.234 (German as used in German)

  • 1 234 (French as used in France)

  • [fancy Arabic example omitted because DevForums won’t let me post those characters )-: ]

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

OFFTOPIC
Hi eskimo,
I added a thread on the forum, could you please help me? Tried to pm you but there is no such function on the site.

Thank you

How to Assign Value of Type Double to Type String?
 
 
Q