-1

I have a json with key and value as "average_cost_for_two": 20

When I want to show this in UI, I was show as Avg Cost for two: 20 However I cannot convert the value to String to append "Avg Cost for two" since the value in the Json is an Int.

Basically I want to do append to the published var like this

for i in fetch.nearby_restaurants{
    DispatchQueue.main.async {
        self.datas.append(datatype(id: i.restaurant.id, name: i.restaurant.name, image: i.restaurant.thumb, rating: "Rating: " + i.restaurant.user_rating.aggregate_rating, cost_for_two: "I want to add my string to show in View here " + i.restaurant.average_cost_for_two,  webUrl: i.restaurant.url))
    }

}

nearby_restaurants has key as "average_cost_for_two": Int

Any help would be greatly appreciated. Thanks!!

2 Answers2

1

The question is not related to SwiftUI at all.

Basically there are two ways:

  1. Type Conversion: String(i.restaurant.average_cost_for_two)

    cost_for_two: "I want to add my string to show in View here " + String(i.restaurant.average_cost_for_two)
    
  2. String Interpolaction: "\(i.restaurant.average_cost_for_two)"

    cost_for_two: "I want to add my string to show in View here \(i.restaurant.average_cost_for_two)"
    

For more information about String Interpolation please read the Language Guide

vadian
  • 232,468
  • 27
  • 273
  • 287
  • Thanks for the response. I was able to solve it. I wanted to keep it general question but thought of just adding the tag for SwiftUI. But thank you so much for responding to my question. – Amith Rampur May 09 '20 at 04:36
0

EDIT: looking at Swift questions elsewhere, this may not be the best approach, from what I found there's a built in method toString allowing for casting to string. (source: https://stackoverflow.com/a/28203312/2932298) it also seems to vary between versions. Some reference a description property after the int: let x = 10.description, although this is getting language-specific.

Coming from someone who has NO experience with Swift, I'm unsure if I'm able to correctly answer this question or not.

However, as a basic principle most (if not all) languages support int -> string conversion, most data types can be converted to a String very simply.

An idea would be something like: String(average_cost_for_two), converting the int value into a String allowing you to concatenate the values.

I believe the technical term would be type casting a most languages have support for this. Again, especially with X -> string conversions.

Again, no Swift experience, just basic programming principles from the different languages I've developed in.

Isolated
  • 1,347
  • 8
  • 12
  • Thank you. I was actually able to solve this based on response from the source thread link you provided. thank you so much. – Amith Rampur May 09 '20 at 04:30