Search code examples
jsonswiftweather-api

How to add variable to url. iOS


I have a problem with adding my variable to url. In code I have this:

self.imgURL = "https://openweathermap.org/img/w/\(self.dodatek).png"

and this doesn't work. In debugger it shows me this:

url String  "https://openweathermap.org/img/w/Optional(\50n\).png"  

but it should be like this:

https://openweathermap.org/img/w/50n.png

When I change my code to this:

self.imgURL = "https://openweathermap.org/img/w/50n.png"

it works, and shows me weather icon,but I want to put there my variable that takes icon name from json.


Solution

  • It looks like self.dodatek is an Opional. You need to unwrap it. I suggest using either if let optional binding, or a guard statement:

    if let filename = self.dodatek {
      self.imgURL = "https://openweathermap.org/img/w/\(filename).png"
    }
    else {
      print("Error. filename in self.dodatek is nil!")
      return
    }