9 February 2024
Swift makes it super easy to create a location. Just give it your latitude and longitude:
let someLocation = CLLocation(latitude: 40, longitude: -40)
Easy! Too easy? The slight catch here is that there is no validation being done. You can create a completely invalid location and Swift won’t complain at all. No compiler errors, no runtime errors. If you log the bad location, you can see the bad values are still maintained:
let badLocation = CLLocation(latitude: 9000, longitude: -9000)
Logger().debug("The location is: \(badLocation)")
---
// The location is: <+9000.00000000,-9000.00000000> +/- 0.00m (speed -1.00 mps / course -1.00) @ 2/9/24, 13:46:53 Central Standard Time
Luckily this is something we don’t have to remember. We can use the CLLocationCoordinate2DIsValid
method. It takes a coordinate and returns a boolean indicating if the coordinate is valid.
let questionableCoordinate = CLLocationCoordinate2D(latitude: -100, longitude: 95)
let isValidCoordinate = CLLocationCoordinate2DIsValid(questionableCoordinate)
print(isValidCoordinate) // spoiler - it's not
// Note the method is for a `CLLocationCoordinate2D`, not a `CLLocation`
let questionableLocation = CLLocation(latitude: -100, longitude: 95)
let isValidLocation = CLLocationCoordinate2DIsValid(questionableLocation.coordinate)
Now you can go on your way with confidence.
Quick aside: When adding an annotation with an invalid coordinate to a SwiftUI Map view I’ve seen couple of different behaviors. Most of the time the annotation just doesn’t show up at all, which is probably the desirable behavior. Occassionally though, the framework seems to transform the invalid coordinate to one at (0,0) - the popular vacation destination of Null Island.