Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting CLLocationDistance in Swift

Tags:

casting

ios

swift

I'm a complete newbie using Swift and I'm having a headache trying to do something that should be quite straightforward.

I have an object Place with a variable of type Double called distance. I'm using the following code to store the distance between the user location and some other locations:

var obj = res as Place
let loc = CLLocation(latitude: obj.location.lat, longitude: obj.location.lng)
let dist = CLLocation.distanceFromLocation(loc)
obj.distance = dist // ERROR 

The last line shows me an error saying "CLLocationDistance is not convertible to 'Double'". As far I know, CLLocationDistance should be a Double. I've tried to cast that value to double and float using

Double(dist)

and

obj.distance = dist as Double

but nothing seems to work. I would appreciate any help.

like image 612
rmvz3 Avatar asked Nov 20 '25 07:11

rmvz3


1 Answers

The reason this is occurring boils down to the following line:

let distance = CLLocation.distanceFromLocation(loc)

This is not doing what you think it's doing. distanceFromLocation is an instance method, but you are calling it as a class method. Unlike ObjC, Swift allows this, but what you're actually getting back is not a CLLocationDistance but a function with the following type signature: CLLocation -> CLLocationDistance. You can verify this by adding in the type annotation yourself:

let distance: CLLocation -> CLLocationDistance = CLLocation.distanceFromLocation(loc)

This is called partial application and is outside the scope of my answer, except to note that the first parameter of the function assigned to distance would be the implicit self when called as an instance method.

The fix is simple:

let distance = loc.distanceFromLocation(loc)

Then everything will work as you desire, at least from the perspective of the type system, because this properly returns a CLLocationDistance, which is substitutable for Double.

like image 194
Gregory Higley Avatar answered Nov 22 '25 22:11

Gregory Higley