Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get rid of Optional() string

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?

like image 979
Utku Dalmaz Avatar asked Apr 08 '26 17:04

Utku Dalmaz


1 Answers

If you unwrap the latitude and longitude values like this...

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if  let lat = manager.location?.coordinate.latitude,
        let long = manager.location?.coordinate.longitude {

        updateloc(String(lat), long: String(long))
    }
}

...then you can avoid optionals altogether in the updateloc function:

func updateloc(lat : String, long : String) {

// code...

    let data = "lat=\(lat)&long=\(long)"
}

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.

like image 78
Aaron Rasmussen Avatar answered Apr 10 '26 07:04

Aaron Rasmussen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!