Mike Mike -3 years ago 393
Swift Question

Best way to protect from lat and lng returning nil on map initialisation swift

In viewDidLoad in a controller that is basically a map I get the lat and lng. But they're optionals and before passing them to the camera I'd really like to check that they're not nil.

var lat = locationManager.location?.coordinate.latitude
var lng = locationManager.location?.coordinate.longitude
let cameraPosition = GMSCameraPosition.camera(withLatitude: lat!,
longitude: lng!, zoom: 1)

mapView = GMSMapview.map(withFrame: CGRect.zero, camera: cameraPosition)

It's not a huge issue but if I use an if let statement or just an if statement to check if lat and lng are nil the prob I end up with is that I need to move the let cameraPosition line and mapView statements all into the if statement...and it's a bit annoying.

Is there a "best practice" way of handling lat lng nils with a google map.


Answer Source

Use guard statements to safely unwrap optionals. Both variables will be non-optional and accessible after the guard statements.

guard let lat = locationManager.location?.coordinate.latitude else {return}
guard let lng = locationManager.location?.coordinate.longitude else {return}
let cameraPosition = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 1)
mapView = GMSMapview.map(withFrame: CGRect.zero, camera: cameraPosition)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download