Function Query

This function seems to be working for me but I want to know if there are any obvious format issues I should deal with?
func getLatitude() -> Double {
let coordinate = self.locationManager.location != nil ? self.locationManager.location!.coordinate : CLLocationCoordinate2D()
return coordinate.latitude}

There is a problem with your function: it is not thread-safe.

The value of locationManager.location could change between when you check it against nil and when you force-unwrap it.

It is better to use optional chaining and nil-coalescing for this type of access:

func getLatitude() -> Double {
  let coordinate = locationManager.location?.coordinate ?? CLLocationCoordinate2D()
  return coordinate.latitude

Also, as a general design question, is there a reason you’ve made this a function rather than a computed property?

Additionally, are you certain that it behaves the way you want when location is nil?

1 Like

Thanks Nevin that helps a lot and your right I don't really need a function so I have done a computed property. Much appreciated