Swift: Create array of coordinates

Viewed 299

I'm trying to create an array where the location of the user will be stored. I tried to use the code below but it won't work, it just change the coordinates inside the array.

func prevcurrLoc(lat : Double, lng: Double) {
    var destination = [[String:Double]]()
        
    let locArray : [String:Double] = ["lat" : lat, "lng" : lng]
        
    destination.append(locArray)
        
    print(destination)
}

I also try the code below, but it work the same, it only change the coordinates inside the array.

func prevcurrLoc(lat : Double, lng: Double) {
        
    var coordArray : [CLLocationCoordinate2D] = []
        
    let latArray = [lat]
    let lngArray = [lng]
        
    if latArray.count == lngArray.count {
         for i in 0 ..< latArray.count {
             let destination = CLLocationCoordinate2DMake(latArray[i], lngArray[i])
                
             coordArray.append(destination)
                
             print(coordArray)
         }
    }
}

I hope you understand what I mean. I am very grateful of any help! Thank you for reading.

1 Answers

You need to have an array declared outside of the function if you want the locations to be remaining after the function has exited.

Assuming you have this function in a struct you need a property for the array

struct LocationData {
    var locations = [CLLocationCoordinate2D]()
     //…
}

And then add locations to this array (I have renamed the function)

struct LocationData {
    var locations = [CLLocationCoordinate2D]()

    func addLocation(latitude: Double, longitude: Double) {
        let destination = CLLocationCoordinate2DMake(latitude, longitude)
        locations.append(destination)
    }                
}
Related