Clumsy Hamster Clumsy Hamster - 1 year ago 79
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,%@&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,(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?


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 "\(sLat),\(sLon)&destination=\(eLat),\(eLon)&sensor=false&units=metric&mode=driving"

Answer Source

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 = "\(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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download