1

I'm currently trying to construct a way that calculates the the distance in feet between my current location and other hard coded locations. I will eventually display these distances as strings in a table view. These are the steps that I'm taking:

1) I have a hard coded library of dictionaries that each hold a "latitude" and "longitude" key-value pair.

2) to extract this information from a struct as follows:

 struct BarDetials {

 // other properties
 ....
 var lat: CLLocationDegrees?
 var long CLLocationDegrees?

 init(index: Int) {
 // initialize other properties
 // ...
 lat = specificBarDetail["latitude"] as! CLLocationDegrees!
 long = specificBarDetail["longitude"] as! CLLocationDegrees!

   }
 }

3) I use another struct to create an array of CLLocation instances from these coordinates as follows:

struct ConstructLocationsToCompare {

var latitude : [CLLocationDegrees?] = []
var longitude : [CLLocationDegrees?] = []
var barLocations : [CLLocation?] = []

init(){
    for index in 0...21 {
        var data = BarDetails(index: index)
        if data.lat != nil {
            latitude.append(data.lat!)
        }
        if data.long != nil {
            longitude.append(data.long!)
        }
        barLocations[index] = CLLocation(latitude: latitude[index]!, longitude: longitude[index]!)
       }

   }
}

4) I then calculate the distances in my MasterViewController().

var latestLocation : AnyObject? , var currentLocation : CLLocation!, and var distanceStringArray : [String?] = [] are all properties of my MasterViewController() class.

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in

        // Get latest location and store it as a property of MasterViewController

        if self.latestLocation != nil {
            self.latestLocation = locations[locations.count - 1]

        // Print out the latest locaiton for debuging

        println("Latest Location")
        println("---------------")
        println(self.latestLocation)


        // Create an instance of ContructLocationsToCompare to get all locaiton data

        var getBarLocations = ConstructLocationsToCompare()

        // Get loop to calculate the distance you are away from each Bar

        var distanceDoubleArray : [Double?] = []

        for index in 0...21 {
            var distanceBetween : CLLocationDistance = self.latestLocation!.distanceFromLocation(getBarLocations.barLocations[index])
            var distanceInFeet = distanceBetween * 3.28084
            distanceDoubleArray[index] = distanceInFeet
            self.distancesStringArray.append( String(format: "%6.0 ft", distanceDoubleArray[index]!))

        }
    }
        //println(distanceBetween) or get error if it exists

        if error != nil {
            println("Error: " + error.localizedDescription)
            return
        }
        if placemarks.count > 0 {
            let pm = placemarks[0] as! CLPlacemark
            self.displayLocationInfo(pm)
        }

    })

}

5) Lastly, to display my distance from each location (in my -cellForRowAtIndexPath):

           println("")
           println("")

           println("List of Locations")
           println("=================")
           println(self.distancesStringArray)

           println("")
           println("")
           println("")
           println("")




                 if self.distancesStringArray[indexPath.row]!.isEmpty == true{    
               futureCell.distanceAway?.text = "-" // I crash at this line ^^^^^^
           } else {
            futureCell.distanceAway?.text = self.distancesStringArray[indexPath.row]
                }

*** My distanceStringArray is always empty therefore I get a fatal error and the app crashes. How do I fix this? Is the fact that I declare var latestLocation : AnyObject? , var currentLocation : CLLocation!, and var distanceStringArray : [String?] = [] properties of my MasterViewController() class bad practice? If not do these properties need to be casted as a different type/ declared in a different manner?

Joe H
  • 13
  • 1
  • 7
  • It really helps to include some information in the `print()`: `println(self.latestLocation)` -> `println("latestLocation: \(self.latestLocation)")`. Also to print a newline just use `"\n"`: Instead of multiple `println("")` just `println("\n\n\n\n")`. Tis is basic "C" stuff. – zaph Aug 29 '15 at 18:19
  • I don't see where you are adding anything to `distanceStringArray`. Also you should **never** get a fail error from an Optional, you must check all Optionals that could ever, under any circumstances, possibly return nil. – zaph Aug 29 '15 at 18:23

0 Answers0