【发布时间】:2019-04-23 07:05:53
【问题描述】:
我正在做一个非常简单的操作。我正在对地图中的一堆位置进行排序以创建一个封闭的圆圈,如下所示:
var maxLong: Double = -180
var maxLat: Double = -180
var minLong: Double = 180
var minLat: Double = 180
for coord in inCoordinates {
maxLong = max(coord.longitude, maxLong)
maxLat = max(coord.latitude, maxLat)
minLong = min(coord.longitude, minLong)
minLat = min(coord.latitude, minLat)
}
let nw: CLLocation = CLLocation(latitude: maxLat, longitude: minLong)
let se: CLLocation = CLLocation(latitude: minLat, longitude: maxLong)
let center = CLLocationCoordinate2D(latitude: (maxLat + minLat) / 2.0, longitude: (maxLong + minLong) / 2.0)
let radiusInMeters = abs(nw.distance(from: se)) / 2.0
return MKCircle(center: center, radius: radiusInMeters)
非常简单(是的,我知道 IDL 问题,但我想保持简单)。
我想知道的是,是否有某种方法可以将循环简化为 reduce 的变体,您最终会得到如下结果:
let enclosingRect: MKMapRect = inCoordinates.magikalReduce {
// Magic Happens Here -Queue Doug Henning GIF
}
所以返回的矩形包含蒸馏点。
是的,我知道我可以简单地扩展 Array(可能带有类型限定符)以使用计算属性来执行此操作,但这有点违背了这样做的目的。以上是相当有效的,我宁愿不增加开销,只是为了花哨(这意味着,即使我能做到,它也可能效率太低而无法使用。
这与其说是技术需求,不如说是一种好奇心探索。上面的代码对我来说很好,而且比较活泼。
【问题讨论】:
标签: swift algorithm mapkit reduce