It is not JSON, so not as easy (thanks to JSONDecoder).
Are you sure Pizzeria La Rocca is not in quotes "Pizzeria La Rocca", idem for XmGjU9gxS5s0CzP4S6-bHw or url ?
A simple way to do this (with the quotes):
| |
| let input : [String: Any] = ["Id": "XmGjU9gxS5s0CzP4S6-bHw", "Name": "Pizzeria La Rocca", "Url": "https://www.yelp.com/biz/pizzeria-la-rocca-seattle?adjust_creative=sxCnBn1t8D3B-4MLGRB_2g&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=sxCnBn1t8D3B-4MLGRB_2g", "Rating": 5.0, "Img": "https://s3-media1.fl.yelpcdn.com/bphoto/kE6hbIfi4WdlIW52SF5KUw/o.jpg"] |
| |
| |
| struct RestaurantListViewModel: Identifiable { |
| var name: String |
| var imageUrl: URL? |
| var id: String |
| var rating: Double |
| var url: String |
| |
| } |
Then use as follows:
| var restaurant = RestaurantListViewModel(name: "", imageUrl: nil, id: "", rating: 0.0, url: "") |
| for (key, value) in input { |
| switch key { |
| case "Name" : restaurant.name = value as? String ?? "" |
| case "Img" : restaurant.imageUrl = URL(string: (value as? String ?? "")) |
| case "Id" : restaurant.id = value as? String ?? "" |
| case "Rating" : restaurant.rating = value as? Double ?? 0.0 |
| case "Url" : restaurant.url = value as? String ?? "" |
| default: break |
| } |
| } |
| |
| print(restaurant) |
And get:
RestaurantListViewModel(name: "Pizzeria La Rocca", imageUrl: Optional(https://s3-media1.fl.yelpcdn.com/bphoto/kE6hbIfi4WdlIW52SF5KUw/o.jpg), id: "XmGjU9gxS5s0CzP4S6-bHw", rating: 0.0, url: "https://www.yelp.com/biz/pizzeria-la-rocca-seattle?adjust_creative=sxCnBn1t8D3B-4MLGRB_2g&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=sxCnBn1t8D3B-4MLGRB_2g")
You can also do this in an init in struct
| struct RestaurantListViewModel: Identifiable { |
| var name: String |
| var imageUrl: URL? |
| var id: String |
| var rating: Double |
| var url: String |
| |
| |
| init(from dictionary: [String: Any]) { |
| self.name = dictionary["Name"] as? String ?? "" |
| self.imageUrl = URL(string: (dictionary["Img"] as? String ?? "")) |
| self.id = dictionary["Id"] as? String ?? "" |
| self.rating = dictionary["Rating"] as? Double ?? 0.0 |
| self.url = dictionary["Url"] as? String ?? "" |
| } |
| } |
And use :
| let input : [String: Any] = ["Id": "XmGjU9gxS5s0CzP4S6-bHw", "Name": "Pizzeria La Rocca", "Url": "https://www.yelp.com/biz/pizzeria-la-rocca-seattle?adjust_creative=sxCnBn1t8D3B-4MLGRB_2g&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=sxCnBn1t8D3B-4MLGRB_2g", "Rating": 5.0, "Img": "https://s3-media1.fl.yelpcdn.com/bphoto/kE6hbIfi4WdlIW52SF5KUw/o.jpg"] |
| let restaurant = RestaurantListViewModel(from:input) |
| |