Clumsy Hamster Clumsy Hamster - 20 days ago 6
Swift Question

How to create a string with format? Not working on string

Lots of details on this throughout SO and online. Unfortunately, I cannot get any of it to work to with my string. I have this string

https://maps.googleapis.com/maps/api/directions/json?origin=%@,%@&destination=%@,%@&sensor=false&units=metric&mode=driving


And all I'm trying to do is insert the necessary values into the string by doing

let url = String(format: Constants.GoogleDirectionsUrl, road.FromCoordinates.Latitude, road.FromCoordinates.Longitude, road.ToCoordinates.Latitude, road.ToCoordinates.Longitude)


The string though always prints out as

https://maps.googleapis.com/maps/api/directions/json?origin=(null),(null)&destination=(null),(null)&sensor=false&units=metric&mode=driving


Although all the coordinates are valid. When I do string interpolation I get the correct value to show up

print("coord -- \(road.FromCoordinates.Latitude)")


coord -- 29.613929

I've tried %l, %f and %@ in the string all with the same results. Anyone see what it is I'm doing incorrect here?

Update

For anyone else, here is what I ended up doing to overcome the above. I followed the answer below a bit and created a class func that I have in one of the global classes in the app. This allows me to call it from any where. Here is the function

class func createUrlDrivingDiretions (sLat: Double, sLon: Double, eLat: Double, eLon: Double) -> String {
return "https://maps.googleapis.com/maps/api/directions/json?origin=\(sLat),\(sLon)&destination=\(eLat),\(eLon)&sensor=false&units=metric&mode=driving"
}

Answer

Why don't you use the following syntax (use Swift... not legacy obj-c coding):

let var1 = "xxx"
let var2 = "yyy"
let var3 = "zzz"
let var4 = "www"
let var5 = "kkk"

let s = "https://maps.googleapis.com/maps/api/directions/json?origin=\(var1),\(var2)&destination=\(var4),\(var5)&sensor=false&units=metric&mode=driving"

Make sure var1... var5 are not optional otherwise you have to unwrap them or you'll get something like this in the output string: Optional(xxx)... instead of xxx

If you need special formatting use NumberFormatter (see this: Formatters)