我有
包含这些内容的地方
print(places)
Optional(Results<Place> <0x109526f30> (
[0] Place {
name = 127 Pine St;
country = United States;
lat = 42.63341130000001;
lon = -71.33169049999999;
},
[1] Place {
name = 138 B St;
country = United States;
lat = 42.6285025;
lon = -71.3288776;
},
[2] Place {
name = 16 Bagley Ave;
country = United States;
lat = 42.6344084;
lon = -71.3378318;
},
[3] Place {
name = 27 Lane St;
country = United States;
lat = 42.6346452;
lon = -71.32436559999999;
},
[4] Place {
name = 39 Cosgrove St;
country = United States;
lat = 42.61964890000001;
lon = -71.3031683;
},
[5] Place {
name = 48 Houghton St;
country = United States;
lat = 42.6252232;
lon = -71.3243308;
},
[6] Place {
name = 49 Coral St;
country = United States;
lat = 42.6359846;
lon = -71.32655780000002;
},
[7] Place {
name = 59 Marriner St;
country = United States;
lat = 42.622121;
lon = -71.31365679999999;
}
)) <<<
我在内存中还有另一个数组,如下所示
print(distances)
["1.74", "1.45", "2.04", "1.50", "0.00", "1.15", "1.64", "0.56"]
结果
我的最终结果如下所示。
代码
这就是我呈现此表的方式
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customPlaceDetailCell", for: indexPath)
as! CustomPlaceDetailCell
if selectedPlace.name != nil {
cell.address.text = (places![indexPath.row]["name"] as! String)
cell.distance.text = distances[indexPath.row]
if indexPath.row == activePlace {
cell.address.isHidden = true
cell.distance.isHidden = true
}
}
return cell
}
我想要
显示按距离从近到远排序的结果
注意:我的距离不是我的地点对象的一部分。我在运行时计算了它们。
一个人会如何去做这件事呢?
最佳答案
计算点之间的距离是昂贵的。您应该只执行一次,或者当您的数据发生变化时。 排序是昂贵的。您应该只执行一次,或者在您的数据发生更改时执行此操作。
尝试对 2 个不同的数组进行排序是一个坏主意。
排序会多次比较数组中的项目。您需要一个地方来节省距离,以便您可以对地点进行排序。
使您的 Place
对象成为具有方法和属性的 Struct
,而不是 Dictionary
。
我会向您的数组添加一个计算距离属性。还要添加一个 internalDistance
属性,该属性是一个 Optional
。
如果 internalDistance
不为 nil,则让计算距离属性的 getter 返回该距离,或者计算距离,将其保存到 internalDistance
,如果为 nil,则返回它。
如果更改目的地点,请循环遍历地点数组并将所有 internalDistance
变量清空,然后重新对地点数组进行排序。
关于ios - 在表格上显示排序结果 - Swift4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53179116/