Search code examples
iosswiftstringintjsondecoder

How can I use JSONDecoder to decode a Int to a String?


I'm parsing a JSON from an API, like this:

let model = try? JSONDecoder().decode(Person.self, from: parsedData) 

// MARK: - Person
struct Person: Codable {
    let position 
    let rank: Int
}

The problem is when I want to set the value of a UILabel with rank, because I want to add a '#', so I have to do it the following way:

labelRank.text = "#" + "\(person.rank)"

when in reality I wanted to do:

labelRank.text = person.rank

So in reality I want to have a custom parse from Int to String. How can I achieve this result?


Solution

  • You can have a computed property rankAsString which would return "#" + "\(rank)" in Person struct as follows.

    struct Person: Codable {
        let position: Int
        let rank: Int
        
        var rankAsString: String {
            return "#" + "\(self.rank)"
        }
    }
    

    And, then use that to populate label like as follows.

    labelRank.text = rankAsString