0

Here is my CountryModel:

struct CountryModel {
    let id = UUID()
    let code: String
    var flagImageUri: String?
    let name: String
    let wikiDataId: String
    var isFaved: Bool = false
}

Here is my CountryModel list:

@Published var countryList: [CountryModel] = []

I want to send new request and get the flagImageUri of the country.

Here is the request code:

func getCountryDetail(_ code: String) {
    let headers = [
        "X-RapidAPI-Key": apiKey,
        "X-RapidAPI-Host": "wft-geo-db.p.rapidapi.com"
    ]

    var request = URLRequest(url: URL(
        string: "https://wft-geo-db.p.rapidapi.com/v1/geo/countries/\(code)")!,
        cachePolicy: .useProtocolCachePolicy,
        timeoutInterval: 10.0
    )

    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers

    let dataTask = URLSession.shared.dataTask(
        with: request
    ) { [weak self] data, _, error in
        if error != nil {
            print(error)
        } else {
            do {
                if let safeData = data {
                    print(safeData.base64EncodedString())
                    let decodedData = try JSONDecoder().decode(CDetail.self, from: safeData)
                    print(decodedData)

                    for country in self!.countryList {
                        if country.code.contains(code) {
                            country.flagImageUri = decodedData.data.flagImageUri
                        }
                    }
                }
            } catch {
                print(error)
            }
        }
    })

    dataTask.resume()
}

In here I'm checking if any item has the country code in list and assign it to its flagImgUri:

for country in self!.countryList {
    if country.code.contains(code) {
        country.flagImageUri = decodedData.data.flagImageUri
    }
}

However, I'm getting an error like this:

Cannot assign to property: 'country' is a 'let' constant

How can I achieve what I want?

Fabio Felici
  • 2,841
  • 15
  • 21
themmfa
  • 499
  • 4
  • 15

0 Answers0