We have an array of coordinates and we want to loop through them to draw a path. This is how it looks with the values hardcoded:
func createPath(){
path.move(to: CGPoint(x: 32.7915055, y: -96.8028408))//1
path.addLine(to: CGPoint(x: 32.79174845, y: -96.80252195))
path.addLine(to: CGPoint(x: 32.7919914, y: -96.8022031))//2
path.addLine(to: CGPoint(x: 32.791501100000005, y: -96.80235195))
path.addLine(to: CGPoint(x: 32.7910108, y: -96.8025008))//3
path.addLine(to: CGPoint(x: 32.791301700000005, y: -96.8020985))
path.addLine(to: CGPoint(x: 32.7915926, y: -96.8016962))//4
path.addLine(to: CGPoint(x: 32.79154905, y: -96.8022685))
}
but we are trying not to hardcode and instead create a function that takes an array of coordinates like this:
func create(coordinates: [CLLocationCoordinate2D]) {
for coordinate in coordinates {
path.move(to: CGPoint(x: coordinate.x, y:coordinate.y))//error
path.addLine(to: CGPoint(x: coordinate.x, y: coordinate.y))//error
}
}
The issue is how to get the first coordinate in array for the "path.move" and then use the additional coordinates to use in the "path.addLine" part of function?
enumerate the array and test its index:
for (index, coordinate) in coordinates.enumerated() {
if index == 0 {
path.move(to: CGPoint(x: coordinate.longitude, y:coordinate. latitude))
} else {
path.addLine(to: CGPoint(x: coordinate.longitude, y: coordinate.latitude))
}
}
also notice that CLLocationCoordinate2D
does not have x
nor y
but longitude
and latitude