I am trying to update users location on server
Using this function
func updateloc(lat : String?, long : String?) {
/code...
let data = "lat=\(lat!)&long=\(long!)"
}
And here is the delegate
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
updateloc(String(manager.location?.coordinate.latitude), long: String(manager.location?.coordinate.longitude))
}
I have Optional("") for lat
and long
variables and cannot get rid of it.
Any idea how to do that?
Why not checking if the location is not
nil
and declare
updateloc()
with non-optional parametersAnd why not
if you're using String Interpolation anyway...
I think you are updating user's location by making an HTTP request with the latitude and longitude values in the query string or body of the request.
There are couple of options you can try:
Nil coalescing operator
Assuming we send empty string in the request for any non-existent value:
Optional binding
Assuming we don't trigger the request for any non-existent value:
By the way it is more readable to pass the location as
CLLocationCoordinate2D
type instead of passing latitude and longitude separately:This is not the exact answer to this question, but one reason for this kind of issue.
In my case, I was not able to remove Optional from a String with "if let" and "guard let".
I case of Any
In case of AnyObject
So use AnyObject instead of Any to remove optional from a string in swift.
updateloc(String(manager.location?.coordinate.latitude), ...)
That code is taking an optional value (
manager.location?.coordinate.latitude
) and then forcing it to a String. This results in the String"Optional(42.0)"
or whatever. It then passes that toupdateloc
.I presume that
latitude
is a Double or similar. You need to handle the optional Double before conversion to a String, something like this:I often put functions similar to
coordToString
as an extension on the model object itself (yourmanager
orlocation
). I'd name themformattedLatitude
or something like that. That way, all the screens in your app will use the same formatting for that value, because they'll all be using the same code to do it. This keeps rules like 'if the latitude is missing, display "---"' together in one place.If you unwrap the latitude and longitude values like this...
...then you can avoid optionals altogether in the
updateloc
function:originalUser2
is right...you should get in the habit of safely unwrapping optionals unless you have a really good reason for force-unwrapping them. And just trying to get rid of the optional so the code will compile is not a good reason.