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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With