【问题标题】:Reverse a for loop of an array反转数组的 for 循环
【发布时间】:2021-04-24 14:26:00
【问题描述】:

我正在尝试创建一个函数,它应该计算每个给定坐标的 90 度和 270 度的坐标。

并将其保存在 arrayLocationOffset 数组中

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

我使用这个 for 循环来执行操作:

 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)")
        
    }

arrayLocationOffset 必须具有特定的序列,否则我无法在 Mapkit 中正确绘制多边形。 为了获得第二个 forLoop 的特定顺序(我计算 RHside),我应该从最后一个数组索引开始计算回到第一个...

这可能吗?

谢谢

【问题讨论】:

    标签: swift xcode coordinates mapkit


    【解决方案1】:

    已解决:

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

    我使用反向索引从头开始...

    【讨论】:

    • 为什么不只是for i in (0..&lt;polypoint).reversed()
    【解决方案2】:

    顾名思义,您可以使用 reversed() 反转数组。

    你的代码比较objective-c-ish。枚举数组的更好方法是快速枚举,因为您实际上不需要索引。

    for coord in arrayLocations { ...
    

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

    但是还有一种 swiftier 方式mapping 数组

    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)")        
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-20
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多