skip to Main Content

I’m try to create a func that should calculate the coordinate at 90deg and 270deg from each of the given coordinate..

and save it in an array of arrayLocationOffset

var arrayLocations : [CLLocationCoordinate2D] =
    [
     CLLocationCoordinate2D(latitude: 45.15055543976834, longitude: 11.656891939801518 ),
     CLLocationCoordinate2D(latitude: 45.154446871287924, longitude: 11.66058789179949),
    ]
// simplify only 2 coordinate

I use this for loop in order to perform the action:

 func createCoordinatePoly() {
        let polypoint = arrayLocations.count
     
        for i in 0..<polypoint {
          
            let coord = arrayLocations[i]
            
            // calc LH
            
            let lhCoord = coord270(coord: coord)
            
            arrayLocationOffset.append(lhCoord)
            
        }
        
        for i in 0..<polypoint { // shuld revers this for loop and get first the last index
            
            let coord = arrayLocations[i]
            
            // calc LH
            
            let RhCoord = coord90(coord: coord)
            
            arrayLocationOffset.append(RhCoord)
            
        }
        
        debugPrint("aggiunto array poly (arrayLocationOffset.count)")
        
    }

The arrayLocationOffset must have a specific sequence otherwise I can’t properly draw a polygon in the Mapkit.
In order get the specific order on the second forLoop (where I calculate RHside) I should start to calculate from last array index back to the first…

is this possible?

thanks

2

Answers


  1. Chosen as BEST ANSWER

    solved:

    var reversIndex = polypoint-1
            for _ in 0..<polypoint {
                
                let coord = arrayLocations[reversIndex]
                
                // calc LH
                
                let RhCoord = coord90(coord: coord)
                
                arrayLocationOffset.append(RhCoord)
                reversIndex -= 1
            }
    
    

    I use a reverse index to start from the end...


  2. As the name implies you can reverse an array just with reversed().

    Your code is rather objective-c-ish. A better way to enumerate the array is fast enumeration because you actually don’t need the index.

    for coord in arrayLocations { ...
    

    and

    for coord in arrayLocations.reversed() { ...
    

    However there is a still swiftier way mapping the arrays

    func createCoordinatePoly() {
        arrayLocationOffset.append(contentsOf: arrayLocations.map{coord270(coord: $0)})
        arrayLocationOffset.append(contentsOf: arrayLocations.reversed().map{coord90(coord: $0)})    
        debugPrint("aggiunto array poly (arrayLocationOffset.count)")        
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search