Casting CLLocationDistance in Swift

I am a complete newbie using Swift and have a headache trying to do something that should be pretty simple.

I have a Place object with a variable of type Double called distance. I am using the following code to store the distance between the user's 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 an error: "CLLocationDistance is not convertible to" Double ". As far as I know, CLLocationDistance must be double. I tried to make this value double and float with

Double(dist)

      

and

obj.distance = dist as Double

      

but nothing works. I would appreciate any help.

+3


source to share


2 answers


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

let distance = CLLocation.distanceFromLocation(loc)

      

It doesn't do what you think it does. distanceFromLocation

is an instance method, but you call it as a class method. Unlike ObjC, Swift allows it, but what you actually return, is not CLLocationDistance

, as a function of the following type signature: CLLocation -> CLLocationDistance

. You can check this by adding to the type annotation yourself:

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

      



This is called private application and is beyond the scope of my answer, except that the first parameter of the function assigned distance

will be implicit self

when called as an instance method.

The fix is ​​simple:

let distance = loc.distanceFromLocation(loc)

      

Then everything will work as you wish, at least in terms of the type system, because it correctly returns CLLocationDistance

which is substituted under Double

.

+8


source


You need two objects CLLocation

with two different locations

How fromLocation

andtoLocation

Then you get the distance in



let distance = fromLocation.distanceFromLocation(toLocation)

      

Example code for distance between old and new location:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    if let firstLocation = locations.first as? CLLocation
    {
        mapView.setCenterCoordinate(firstLocation.coordinate, animated: true)

        let region = MKCoordinateRegionMakeWithDistance(firstLocation.coordinate, 1000, 1000)
        mapView.setRegion(region, animated: true)

        if let oldLocation = oldLocation {
            let delta: CLLocationDistance = firstLocation.distanceFromLocation(oldLocation)
            totalDistane += delta
            updateDistanceLabel()
        }

        oldLocation = firstLocation
    }
}

      

+2


source







All Articles