按Double Value Swift对字典排序

时间:2018-11-13 18:01:43

标签: arrays swift dictionary

我有一个包含地名和坐标的Firebase数据库,已将它们都提取,并将它们分别放入自己的Array,然后放入Dictionary,我希望将Dictionary排序为最近的位置/最低的Double

我查看了之前提出的大量问题,但似乎无法弄清楚我在做什么错。当我打印字典时,它按照字母顺序对其进行排序(交叉检查了我知道它们是正确的(实际)距离)。

我该如何按最低Double的价格订购?

var placeName = ""
var distanceArray = [Double]()
var nameDistanceDictionary = [String:Double]()

内部从Firebase提取数据

self.placeName = placeSnap.key

let distanceRound = Double(round(10*distance)/10)
self.distanceArray.append(distanceRound)
self.nameDistanceDictionary = [self.placeName:distanceRound]
print(self.nameDistanceDictionary)


//Prints (example Doubles)
["Ascot": 5.5]
["Birmingham": 1.2]
["Bristol" : 18.6]
["London": 0.3]
["Manchester": 40.2]
["Newcastle": 2.4]

我已经尝试过(此打印与上面的内容相同,减去了[""]

for (k,v) in (Array(self.nameDistanceDictionary).sorted {$0.1 < $1.1}) {
    print("\(k):\(v)")
    }

2 个答案:

答案 0 :(得分:3)

词典中的每个项目都有两个属性: more about dictionary here

您不必从字典中创建Array。只需按项目值对字典进行排序即可。

.sorted(by: {$0.value < $1.value})

现在为每个循环创建一个,而不是创建k而不是创建vitem,它将代表字典中的每个项目。

for item in ...

现在,如果您要打印值,也只需使用键即可

print(item.value)

print(item.key)

为每个循环替换整体:

for (k,v) in (Array(self.nameDistanceDictionary).sorted {$0.1 < $1.1}) {
    print("\(k):\(v)")
}

与此

for item in nameDistanceDictionary.sorted(by: {$0.value < $1.value}) {
    print("\(item.key):\(item.value)")
}

答案 1 :(得分:1)

如果将模型存储为struct而不是尝试进行Dictionary修改,那么您的生活会容易得多。尝试这样的事情:

struct Place {
    let name: String
    let distance: Double
}

let places = [Place(name: "Ascot", distance: 5.5),
              Place(name: "Birmingham", distance: 1.2),
              Place(name: "Bristol", distance: 18.6),
              Place(name: "London", distance: 0.3),
              Place(name: "Manchester", distance: 40.2),
              Place(name: "Newcastle", distance: 2.4)]

for place in places.sorted(by: { $0.distance < $1.distance }) {
    print(place.name)
}