在地图初始化swift上保护免受lat和lng返回nil的最佳方法

时间:2022-11-02 21:18:11

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.

在控制器中的viewDidLoad中,基本上是一个map,我得到了lat和lng。但他们是选择,在将它们传递到相机之前,我真的很想检查它们是不是零。

 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.

这不是一个大问题,但是如果我使用if let语句或只是if语句来检查lat和lng是否为n,我最终得到的问题是我需要将let cameraPosition行和mapView语句全部移动到if语句中......而且有点烦人。

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

是否有一种“最佳实践”方式处理lat lng nils与谷歌地图。

Thanks.

谢谢。

1 个解决方案

#1


1  

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

使用保护语句安全地解包选项。这两个变量都是非可选的,并且可以在guard语句之后访问。

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)

#1


1  

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

使用保护语句安全地解包选项。这两个变量都是非可选的,并且可以在guard语句之后访问。

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)